3

In this insertion sort implementation, is the line arr[pre + 1] = curr; optional?
Since we are already swapping elements inside the while-loop, won't the current element automatically reach its correct position without explicitly assigning it at the end?”

void insertionSort(int* arr, int n) {
    for (int i = 1; i < n; i++) {
        int curr = arr[i];
        int pre = i - 1;
        while (pre >= 0 && arr[pre] > curr) {
            swap(arr[pre], arr[pre + 1]);
            pre--;
        }
        // arr[pre+1] = curr; is this line optional ?
    }
}
New contributor
SHIVRAJ SINGH DEORA is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
4
  • 5
    Follow the code through on paper. Do it with and without that line that you aren't understanding, and see the difference. Pen and paper is a great tool for understanding algorithms Commented Nov 18 at 12:48
  • 2
    Side note : int* arr, int n C++ has std::span for this. Or use std::vector<int>&. Do not represent arrays by passing around pointers (that's so pre C++98) Commented Nov 18 at 12:49
  • 1
    godbolt.org/z/KaxKn1b1M Commented Nov 18 at 13:19
  • @MarekR Or with std::span : godbolt.org/z/aGcfzPMcY Commented Nov 18 at 14:25

1 Answer 1

5

In your implementation the commented line is in fact not crucial to sort the array. The thing is, by using swap() your'e doing something more similar to bubble sort - moving curr left until it matches the sorted part. The "actual" insertion sort would instead push all elements right and add curr to the empty space left at pre+1:

// a std::vector<int>& is also a good option - thx comments
void insertionSort(int* arr, int n) {
    for (int i = 1; i < n; i++) {
        int curr = arr[i];
        int pre = i - 1;
        while (pre >= 0 && arr[pre] > curr) {
            arr[pre+1] = arr[pre];
            pre--;
        }
        arr[pre+1] = curr; // now it's important
    }
}

I think this approach is better than swapping because of the reduction of assignments per element sorted - swap() uses a temp variable.

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

2 Comments

Note that in the general case, this "reduction of assignments" optimization may actually make performance worse. To fix that, use std::move. Not needed in the specific case of int.

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.