Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ vector insertion sort algorithm method - pass vector into method

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

like image 585
Tanya Tazzy Hegarty Avatar asked Feb 13 '26 06:02

Tanya Tazzy Hegarty


1 Answers

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) 
like image 55
GManNickG Avatar answered Feb 14 '26 19:02

GManNickG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!