Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Modify the source code for the insertion sort so that it can sort a list of inte

ID: 3675431 • Letter: M

Question

Modify the source code for the insertion sort so that it can sort a list of integers. Is there a difference in performance (compared to the vector-based one)?

#include <iostream>
#include <vector>
#include <list>
#include <cstdlib>

using namespace std;

void insertion_sort(std::vector <int> &num) {
   int i, j, key;
   bool insertionNeeded = false;

   for (j = 1; j < num.size(); j++) {
       key = num[j];
       insertionNeeded = false;
       for (i = j - 1; i >= 0; i--) { // larger values move right

           if (key < num[i]) {
               num[i + 1] = num[i];
               insertionNeeded = true;
           }
           else
               break;
       }
       if (insertionNeeded)
           num[i + 1] = key; //Put key into its proper location
   }
}

Explanation / Answer

example output:

b) There is no speedup as such. But the linked list implementation takes the double amount of memory than vector one.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote