mercredi 7 juin 2017

Getting potential memory errors I guess - "double free or corruption"

I get the error only with negative numbers while it works for all positive numbers. Not really sure what is wrong here. Any help/guidance much appreciated.

#include <vector>
#include <iostream>
#include <algorithm>

int insertionSort(std::vector<int> &array){
    // Count the number of shifts needed to sort the array
    int shifts = 0;
    for(int i = 1; i < array.size(); i++){
        if(array[i] < array[i - 1]){
            int j = i;
            while(array[i] < array[i - 1] && i >= 0){
                shifts++;
                std::swap(array[i], array[i - 1]);
                i--;
            }
            i = j;
        }
    }
    return shifts;
}

int main(){
    std::vector<int> array = {-1, -2}; // This won't work
    //std::vector<int> array = {1, 2}; // This works
    int shifts = insertionSort(array);
    std::cout << shifts;

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire