C++ Insertion Sort crashing

93 Views Asked by At

I create a vector and fill it with random integers. I then print out all the unsorted values and call insertionSort(). After this call, the numbers should be printed in sorted order. My program keeps crashing and I'm not sure why.

Here's my code:

#include <cstdlib>
#include <iostream>
#include <vector>
#include <time.h>

using namespace std;

int listSize;

vector<int> intList()
{
    cout << "How many numbers do you want to sort?\n";
    cin >> listSize;
    vector<int> list;
    for (int i = 0; i < listSize; i++)
    {
        int random = rand() % 10001;
        list.push_back(random);
    }

    return list;
};

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

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

int main(int argc, char** argv)
{
    srand(time(0));
    vector<int> list = intList();
    for (vector<int>::iterator it = list.begin(); it != list.end(); it++)
    {
        cout << *it << " ";
    }
    cout << "\n";

    insertionSort(list);

    for (vector<int>::iterator it = list.begin(); it != list.end(); it++)
    {
        cout << *it << " ";
    }

}
2

There are 2 best solutions below

0
On

This

for (i = 1; data.size(); i++)

should be:

for (i = 1; i<data.size(); ++i)

Otherwise the for never breaks.

0
On

Your for loop doesn't check break condition, and loops forever starting to write out of bounds.

for (i = 1; data.size(); i++)

You should check if i is smaller than the size of the vector.

for (i = 1; i < data.size(); i++)