C++ vector insertion sort algorithm method - pass

2019-07-15 11:09发布

问题:

Ive look everywhere and whatever algorithm I find (if any lol) for insertion sort on a vector in c++, it wont work so im assuming it has something to do with my code. Can anyone help me find a way I can pass a vector into a method as an argument and then do an insertion sort on it? At the moment it waits for a few seconds and shows all the values unsorted :(

Insertion Sort Code

void insertionSort (vector<int> data, int n) 
{
int i, j, tmp;

 for (i=1; i<n; i++)
 {
     j=i;
     tmp=data[i];
     while (j>0 && tmp<data[j-1])
     {
           data[j]=data[j-1];
           j--;
     }
     data[j]=tmp;
 }

The important part of the code

        cout << "insertion sort" << endl;
        system("pause");
        insertionSort(numberVectors, i);

let me know if you dont think theres anything wrong with that code and you want me to show you more, should just be this bit though, the other stuff is irrelavent i think

thanks

回答1:

Your function accepts its argument by value; this means it gets a copy. You sort the copy, in vain.

Change it to a reference instead:

void insertionSort (vector<int>& data, int n) 


回答2:

Pass your array by reference, then changes in the function will be reflected on it

void insertionSort (vector<int> &data, int n) 
{
   ...
}