Complete-Preparation

๐ŸŽ‰ One-stop destination for all your technical interview Preparation ๐ŸŽ‰

View the Project on GitHub

Quick Sort

Code


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);
    }
}

First element as pivot

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;
}

Analysis

Important note

Why Quick Sort is preferred over MergeSort for sorting Arrays ?

Why MergeSort is preferred over QuickSort for Linked Lists ?

How to optimize QuickSort so that it takes O(Log n) extra space in worst case?

Iterative Quick Sort

Reference