1

When sorting an vector using an implementation of insertion sort, the array I passed as an argument doesn't change as a result.

I've tried this before and can't find my issue, some help would be appreciated.

#include <iostream>
#include <vector>
#include <cstdlib>
#include <algorithm>
using namespace std;
void insertionSort(vector<int> arr);
int main() {
    vector<int> vec;
    const int arrSize = 5;
    for(int i = 0; i < arrSize; i++) {
        vec.push_back(rand() % 10); // 3 6 7 5 3
    }
    for (auto i : vec) cout << i << endl; // 3 6 7 5 3
    insertionSort(vec);
    for (auto i : vec) cout << i << endl; // 3 6 7 5 3
}

void insertionSort(vector<int> arr) {
    for(int i = 0; i < arr.size() - 1; i++) {
        int j = i + 1;
        while(j > 0 && arr[j - 1] > arr[j]) {
            swap(arr[j - 1], arr[j]);
            j--;
        }
    }
    for (auto i : vec) cout << i << endl; // 3 3 5 6 7
}

1 Answer 1

3

Arguments are copied by value unless a reference is passed. To modify the object you pass in, use a reference instead.

Pass a vector<int> &arr instead of a mere vector<int> arr. Note the &.

Another way, would be to return the sorted array and assign it to your old, unsorted array.


Some tips:

  1. Prior to rand, call srand to initialize the PRNG with a seed. Since C++11, there is also <random>, which you should favor anyway.

  2. std::endl flushes the stream buffer. '\n' does not, but has the same visual effect. Favor '\n' unless you actually want to flush the stream buffer. Especially in loops, where repeated flushing is superfluous and inefficient.

  3. Use the appropriate size type for STL data structures. For std::vector, this is std::vector<T>::size_type a.k.a. std::size_t. The same as for arrays, BTW. Instead of int, use std::size_t. std::vector::size also returns a std::size_t, not an int.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.