1

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);
    }
}
2
  • If you look carefully, you can notice that if the while loop does more than one iteration, it will not compare the same value on second iteration as arr[i]is modified by the line arr[j + 1]. You set j to i - 1 the then modify arr[j + 1] which is the location of arr[i]since j == i - 1 implies that j + 1 == i. You can also use a debugger to follow the program step by step. Commented Mar 16, 2021 at 1:58
  • Review the order of the two tests in arr[j]>current && j>=0. Commented Mar 16, 2021 at 2:16

1 Answer 1

1

They are not the same because you are making operations on the array arr in your while loop, through index i, and potentially writing a new value into array[i] when j+1 == i, that is why you need to save the current value of arr at index i before the while loop.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.