recently, I learned how to use insertion sort. So, i started tinkering with its code.
#include<bits/stdc++.h>
using namespace std;
int main(void)
{
int arr[] = {4,3,2,10,12,1,5,6};
int n = sizeof(arr)/sizeof(arr[0]);
for(int i=1; i<n; i++)
{
int key = arr[i]; // line a
int j = i-1;
while(j>=0 && arr[j]>key) //line b
{
arr[j+1] = arr[j];
j--;
}
arr[j+1] = key; //line c
}
for(int i=0; i<n; i++)
{
cout<<arr[i]<<" ";
}
}
since key = arr[i], I removed "line a" and placed arr[i] instead of key at "line b" and "line c". I expected the same outcome, but the output is [4 4 4 10 12 12 12 12] which is wrong. Why did this happen?