79823377

Date: 2025-11-18 12:59:45
Score: 0.5
Natty:
Report link

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.

Reasons:
  • Blacklisted phrase (1): thx
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Low reputation (0.5):
Posted by: Proteus