๐ One-stop destination for all your technical interview Preparation ๐
int partition(vector<int>& arr, int l, int r)
{
int pivot = arr[r]; // last element as pivot
int i = l - 1; // index of smaller element
for (int j = l; j < r; j++) {
// if current element is smaller than the pivot
if (arr[j] <= pivot) {
swap(arr[i + 1], arr[j]);
i++; // increment index of smaller element
}
}
swap(arr[i + 1], arr[r]);
return i + 1;
}
void quickSort(vector<int>& arr, int l, int r)
{
if (l < r) {
int pi = partition(arr, l, r);
quickSort(arr, l, pi - 1);
quickSort(arr, pi + 1, r);
}
}
int partition(vector<int>& arr, int l, int r)
{
int pivot = arr[l]; // first element as pivot
int i = l, j = r;
while (i < j) {
while (arr[i] <= pivot && i < r)
i++;
while (arr[j] > pivot && j > l)
j--;
if (i < j) {
swap(arr[i], arr[j]);
}
}
swap(arr[l], arr[j]);
return j;
}