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:
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 recursionUsed pivot as index instead of value
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...
- 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