Overview: I am trying to write a program that generates an array of randomly generated integers, and sorts them as the array is being generated. I've just used 7 elements in the following example, as it's easier to check for errors that way.
Code:
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
void sortArray(int array[], int size) {
int i, j, tmp;
for (i = 1; i < size; i++) {
j = i;
while (j > 0 && array[j - 1] > array[j]) {
tmp = array[j];
array[j] = array[j - 1];
array[j - 1] = tmp;
j--;
}
}
}
int main()
{
int nums[7];
srand(time(NULL)); //seeding with the system time
for (int i=0; i<7; i++){
nums[i]=rand();
sortArray(nums, i);
}
for (int t=0; t<7; t++) cout << nums[t] << " ";
return 0;
}
Output: It appears to sort the numbers into ascending order, but the last number outputted is not where it should be - it isn't the highest number. I'm sure it's something simple but I can't spot it. Here's an example output:
1906 4950 15321 .... 29951 10910
Thank you.