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 << " ";
}
}
This
should be:
Otherwise the
for
never breaks.