Quick Sort

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
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容