LeetCode/LintCode

Quick Sort

2025-10-19  本文已影响0人  greatseniorsde
public:
    vector<int> sortArray(vector<int>& arr) {
        quickSort(arr, 0, arr.size() - 1);
        return arr;
    }


    void quickSort(vector<int>& arr, int start, int end){
        if (start >= end){
            return;
        }
         int pivot = arr[(start + end)/2];
        int l = start;
        int r = end;
       

        while (l <= r){

            while (l <= r && arr[l] < pivot){
                l++;
            }
             while (l <= r && arr[r] > pivot){
                r--;
            }

            if (l <= r){
                int temp = arr[l];
                arr[l] = arr[r];
                arr[r] = temp;
                l++;
                r--;
            }
        }

        quickSort(arr, start, r);
        quickSort(arr, l, end);

    }
};

Common problems:

  1. start and end are modified during partitioning, so after the loop:
    start and end have crossed over and lost their original meaning
    You can't use them as boundaries for recursion

  2. Used pivot as index instead of value

  3. While (left < right) instead of while (left <= right)
    eg.
    With while (l < r) on [3,2,1,4,5]:
    Partition boundaries overlap
    Leads to infinite recursion on subarray [0,1]
    Causes stack overflow or wrong answer
    Stack grows:
    quickSort(0,1)
    calls quickSort(0,1) again
    calls quickSort(0,1) again...

  1. While (left <= right && A[left] <= pivot)
    Eg. 111111
    will end up with these regursive calls
    quickSort(arr, start=0, r=5) → same as original!
    quickSort(arr, l=6, end=5) → invalid (base case)
    <= causes left pointer to run past the array
    Because l overshoots, the right loop never executes
    So r never moves — stays at end
    Thus, left partition is still the full array → infinite recursion
上一篇 下一篇

猜你喜欢

热点阅读