I am implementing a simple Insertion Sort in C++ shown below:
void insertion_sort(int a[], int size)
{
int temp;
for (int i = 2; i < size; i++)
{
temp = a[i];
int j = i - 1;
while (j > 0 && a[j] > temp)
{
a[j + 1] = a[j];
j--;
}
a[j + 1] = temp;
print_array(a, size);
}
cout << "Final:" << endl;
print_array(a, size);
}
However, this sorts all elements in my array apart from the first element. This is what the output looks like:
Original array:
5 2 4 1 3 0
Insertion Sorted array:
5 2 4 1 3 0
5 1 2 4 3 0
5 1 2 3 4 0
5 0 1 2 3 4
Final:
5 0 1 2 3 4
If I change
j > 0
to
j >= 0
then,
Original array:
5 2 4 1 3 0
Insertion Sorted array:
5 2 4 1 3 0
1 5 2 4 3 0
1 5 2 3 4 0
0 1 5 2 3 4
Final:
0 1 5 2 3 4
for (int i = 1; i < size; i++)