Feb 6, 2019 at 9:04am Feb 6, 2019 at 9:04am UTC
Hello friends,
Im pretty stumped, not sure where I'm going wrong. Sometimes I get the correct output and other times if I switch the numbers around in an array it will output correct, but on subsequent run, it's incorrect.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
void insertSort(int A[], int size)
{
int j = 0;
int temp = 0;
//SORT ARRAY
for (int i = 0; i < size; ++i)
{
j = i + 1;
while (j > 0 && A[j] < A[j-1])
{
temp = A[j];
A[j] = A[j-1];
A[j-1] = temp;
j--;
}
}
//PRINT SORTED ARRAY
for (int i = 0; i < size; ++i)
{
cout << A[i] << " " ;
}
cout << "\n" ;
}
Last edited on Feb 6, 2019 at 9:05am Feb 6, 2019 at 9:05am UTC
Feb 6, 2019 at 9:17am Feb 6, 2019 at 9:17am UTC
When i is size-1 , then j will be equal to size , which means A[j] is out of bounds.
Feb 6, 2019 at 6:23pm Feb 6, 2019 at 6:23pm UTC
Thank you, I will go ahead and fix that.