NOIDATUT FREE E LEARNING PLATFORM • AKTU B.TECH

Quick Sort

Quick sort is a divide-and-conquer sorting algorithm that picks a pivot element, partitions the array so smaller items go left and larger items go right, and recursively sorts both sides. It averages O(n log n) time and O(log n) stack space, with O(n²) wo


Theory & Explanation

Quick Sort: Definition, Stepwise Working, Complexity & Code

1. Definition & Key Characteristics

Quick Sort is a fast, comparison-based sorting algorithm based on the Divide and Conquer paradigm. It selects an element called a pivot and partitions the array around the pivot so that elements smaller than (or equal to) the pivot are placed on its left and elements greater than the pivot are placed on its right. The pivot then sits at its final sorted position, and the algorithm recursively applies the same process to the left and right sub-arrays.

  • In-Place Sorting: Partitioning rearranges elements within the array using a few index/swap variables, requiring only O(log2 n) average call-stack space (and O(n) in the worst case for skewed recursion).
  • Not Stable (in Standard Partition): Swapping elements across a pivot can change the relative order of equal keys.
  • Cache-Friendly & Fast in Practice: Operates sequentially on contiguous memory and typically outperforms Merge Sort in practice for in-memory arrays despite its O(n2) worst case.
  • Pivot Selection Matters: Choosing the pivot as the first, last, middle, or random element (or median-of-three) affects partition balance and worst-case avoidance.

2. How Quick Sort Works (Step-by-Step Algorithm — Lomuto Partition Scheme)

  1. Base Case: If low >= high (sub-array has 0 or 1 element), return immediately—it is already sorted.
  2. Choose Pivot: Select the last element as pivot: pivot = arr[high].
  3. Initialize Partition Boundary: Set i = low - 1 (tracks the end of elements smaller than or equal to pivot).
  4. Scan & Swap: Loop j from low to high - 1:
    • If arr[j] <= pivot, increment i = i + 1 and swap arr[i] with arr[j].
  5. Place Pivot: After the loop ends, swap arr[i + 1] with arr[high] (the pivot). Now the pivot is at its final sorted index pi = i + 1.
  6. Recurse: Recursively call quickSort(arr, low, pi - 1) and quickSort(arr, pi + 1, high).

3. Step-by-Step Example & Graphical Representation

Sort arr = [30, 10, 50, 20, 40] (n = 5) in ascending order using pivot = last element:

  • Call 1 on [30, 10, 50, 20, 40] (low = 0, high = 4, pivot = 40):
    • 30 ≤ 40 → i = 0, swap 30 with 30.
    • 10 ≤ 40 → i = 1, swap 10 with 10.
    • 50 > 40 → no swap.
    • 20 ≤ 40 → i = 2, swap 50 with 20 → [30, 10, 20, 50, 40].
    • Swap arr[i + 1] (50 at index 3) with pivot (40 at index 4) → [30, 10, 20, 40, 50].
    • 40 is now fixed at index 3! Left sub-array: [30, 10, 20] (indices 0..2); Right sub-array: [50] (index 4, size 1 → already sorted).
  • Call 2 on Left Sub-array [30, 10, 20] (low = 0, high = 2, pivot = 20):
    • 30 > 20 → no swap; 10 ≤ 20 → i = 0, swap 30 with 10 → [10, 30, 20].
    • Swap arr[1] (30) with pivot (20) → [10, 20, 30].
    • 20 is fixed at index 1! Left [10] and Right [30] are single elements, so the entire array becomes [10, 20, 30, 40, 50].

Graphical Representation: Stepwise Partitioning of Quick Sort on [30, 10, 50, 20, 40]

Quick Sort Partition Trace (Pivot = Last Element, Ascending) Start: 30 10 50 20 40 Pivot = 40 (last element) Part 1: 30 10 20 40 50 40 settled at idx 3; <40 left, >40 right Part 2: 10 20 30 40 50 Pivot 20 settled at idx 1; 10 & 30 sorted Final: 10 20 30 40 50 Sorted: [10, 20, 30, 40, 50] Amber = chosen pivot | Green = pivot placed at final sorted position | Blue/Purple = sub-array partitions

4. Time & Space Complexity Analysis

Case Condition Recurrence Time Complexity
Best Case Pivot always splits the array into two nearly equal halves T(n) = 2T(n/2) + O(n) O(n log2 n)
Average Case Randomly ordered elements (balanced splits on average) T(n) ≈ T(k) + T(n - k - 1) + O(n) O(n log2 n)
Worst Case Pivot repeatedly gives maximally skewed splits (e.g., sorted/reverse array with fixed end pivot) T(n) = T(n - 1) + O(n) O(n2)

Auxiliary Space Complexity: O(log2 n) average recursion stack space; O(n) in the worst case (can be kept O(log2 n) worst-case stack by recursing on the smaller partition first and iterating on the larger one).

5. C Program: Quick Sort

#include <stdio.h>

void swap(int a, int b) {
    int temp = a;
    a = b;
    b = temp;
}

int partition(int arr[], int low, int high) {
    int pivot = arr[high]; // Choose last element as pivot
    int i = low - 1;       // Index of smaller element

    for (int j = low; j < high; j++) {
        if (arr[j] <= pivot) {
            i++;
            swap(&arr[i], &arr[j]);
        }
    }
    swap(&arr[i + 1], &arr[high]);
    return i + 1; // Final sorted index of pivot
}

void quickSort(int arr[], int low, int high) {
    if (low < high) {
        int pi = partition(arr, low, high);
        quickSort(arr, low, pi - 1);
        quickSort(arr, pi + 1, high);
    }
}

void printArray(int arr[], int n) {
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

int main() {
    int arr[] = {30, 10, 50, 20, 40};
    int n = sizeof(arr) / sizeof(arr[0]);

    printf("Original array: ");
    printArray(arr, n);

    quickSort(arr, 0, n - 1);

    printf("Sorted array (Ascending): ");
    printArray(arr, n);

    return 0;
}

Expected Output (C):

Original array: 30 10 50 20 40 
Sorted array (Ascending): 10 20 30 40 50 

6. Python Program: Quick Sort

def partition(arr, low, high):
    pivot = arr[high]
    i = low - 1

    for j in range(low, high):
        if arr[j] <= pivot:
            i += 1
            arr[i], arr[j] = arr[j], arr[i]

    arr[i + 1], arr[high] = arr[high], arr[i + 1]
    return i + 1


def quick_sort(arr, low=0, high=None):
    if high is None:
        high = len(arr) - 1

    if low < high:
        pi = partition(arr, low, high)
        quick_sort(arr, low, pi - 1)
        quick_sort(arr, pi + 1, high)

    return arr


if __name__ == "__main__":
    data = [30, 10, 50, 20, 40]
    print("Original array:", data)
    sorted_data = quick_sort(data[:])
    print("Sorted array (Ascending):", sorted_data)

Expected Output (Python):

Original array: [30, 10, 50, 20, 40]
Sorted array (Ascending): [10, 20, 30, 40, 50]
Advertisement
Advertisement