In this insertion sort technique, in the while loop condition when I compare current and arr[j], the program works but if I compare arr[i] with arr[j] the program doesn't give the correct output.
Do you have any idea there's a difference although current and i are same?
void insertionSort(int arr[], int s){
for(int i=1;i<s;i++){
int current = arr[i];
int j=i-1;
while(arr[j]>current && j>=0){// if I use arr[i] instead of current the program gives wrong output.
arr[j+1] = arr[j];
j--;
}
arr[j+1] = current;
printArray(s, arr);
}
}
whileloop does more than one iteration, it will not compare the same value on second iteration asarr[i]is modified by the linearr[j + 1]. You setjtoi - 1the then modifyarr[j + 1]which is the location ofarr[i]sincej == i - 1implies thatj + 1 == i. You can also use a debugger to follow the program step by step.arr[j]>current && j>=0.