Skip to content
Azhimathi Mayam logoDSA Study HubPCCST303 · KTU · S3
Module 4 · syllabusAsked 3× in KTU papersChecked by code · teacher review pending

Quick sort

Partition around a pivot, then recursively sort the two sides.

Syllabus says: “Quick Sort”

On this page · 18 sections
ormakkurippu ✎
Never-forget card

PIVOT → PARTITION (smaller left, bigger right) → RECURSE on both sides. Bad pivot every time → O(n²).

Picture it

A teacher picks one student's mark as the pivot and says ‘below this, go left; above this, go right’ — then repeats inside each group.

Write this in the exam

Quick sort chooses a pivot, partitions the array so that elements smaller than the pivot are on its left and larger ones on its right, and recursively sorts the two parts.

Learning objectives

  • Partition an array around a pivot using both common schemes.
  • Trace the recursion tree.
  • Explain why the worst case is O(n²) and the average case O(n log n).

Prerequisites

Recursion, swapping, divide-and-conquer.

Introduction

Quick sort picks one element — the pivot — and rearranges the array so that everything smaller is on its left and everything larger on its right. The pivot is then in its final position, and the two sides are sorted independently.

Definition

Definition

Quick sort is a divide-and-conquer, in-place sorting algorithm: partition a[lo..hi] around a pivot p so that a[lo..p−1] ≤ a[p] ≤ a[p+1..hi], then recursively sort a[lo..p−1] and a[p+1..hi].

Two partition schemes you may be asked

1. First element as pivot (textbook / Horowitz)

i starts at lo and moves right until a[i] ≥ pivot; j starts at hi+1 and moves left until a[j] ≤ pivot. If i < j swap them and continue. When the pointers cross, swap the pivot a[lo] with a[j].

2. Last element as pivot (Lomuto / CLRS)

Keep a boundary i (initially lo−1). Scan j from lo to hi−1; whenever a[j] ≤ pivot, increment i and swap a[i] with a[j]. Finally swap a[i+1] with the pivot.

Exam tipIn the exam

If the question does not say which pivot to use, state your choice in one line. Intermediate arrays depend on the scheme; the final sorted output does not.

Worked example

Worked example (Horowitz's example keys): 26, 5, 37, 1, 61, 11, 59, 15, 48, 19checked by code
Input26 5 37 1 61 11 59 15 48 19
After partition 1 (pivot 26)11 5 19 1 15 26 59 61 48 37
After partition 2 (pivot 11)1 5 11 19 15 26 59 61 48 37
After partition 3 (pivot 1)1 5 11 19 15 26 59 61 48 37
After partition 4 (pivot 19)1 5 11 15 19 26 59 61 48 37
After partition 5 (pivot 59)1 5 11 15 19 26 48 37 59 61
After partition 6 (pivot 48)1 5 11 15 19 26 37 48 59 61

Totals: comparisons = 29, swaps = 9, partitions = 6

Now watch it run

Every frame comes from really running the algorithm on your input — change it and break it! Tap ▶ Play, or step one frame at a time with ◀ ▶.

Loading visualizer…

Also try: Quick sort, last element as pivot

Algorithm

AlgorithmQuick Sort (first element as pivot)
  1. Step 1:
    Start.
  2. Step 2:
    Read the number of elements n and the n elements into the array A.
  3. Step 3:
    Call QuickSort(A, 0, n-1).
  4. Step 4:
    QuickSort(A, low, high): if low < high, go to Step 5; otherwise return.
  5. Step 5:
    Set pivot = A[low], i = low + 1 and j = high.
  6. Step 6:
    Repeat while i <= j:
    • While i <= high and A[i] <= pivot, increment i.
    • While A[j] > pivot, decrement j.
    • If i < j, swap A[i] and A[j].
  7. Step 7:
    Swap A[low] and A[j]. The pivot is now in its final position j.
  8. Step 8:
    Call QuickSort(A, low, j-1).
  9. Step 9:
    Call QuickSort(A, j+1, high).
  10. Step 10:
    When the call in Step 3 is finished, display the sorted array A.
  11. Step 11:
    Stop.

Test i <= high before A[i] <= pivot. If every element is ≤ the pivot, i moves past the end, and testing A[i] first would read outside the array.

AlgorithmQuick Sort (last element as pivot)
  1. Step 1:
    Start.
  2. Step 2:
    Read the number of elements n and the n elements into the array A.
  3. Step 3:
    Call QuickSort(A, 0, n-1).
  4. Step 4:
    QuickSort(A, low, high): if low < high, go to Step 5; otherwise return.
  5. Step 5:
    Call p = Partition(A, low, high).
  6. Step 6:
    Call QuickSort(A, low, p-1).
  7. Step 7:
    Call QuickSort(A, p+1, high).
  8. Step 8:
    Partition(A, low, high): set pivot = A[high] and i = low - 1.
  9. Step 9:
    Repeat for j = low to high-1:
    • If A[j] <= pivot, increment i and swap A[i] and A[j].
  10. Step 10:
    Swap A[i+1] and A[high], and return i + 1 (the final position of the pivot).
  11. Step 11:
    When the call in Step 3 is finished, display the sorted array A.
  12. Step 12:
    Stop.
Pseudocode used by the animated lab · the lines highlighted in the visualizer
Quick sort — first element pivot
  1. 1QuickSort(a, lo, hi)
  2. 2if lo < hi
  3. 3pivot ← a[lo]; i ← lo; j ← hi + 1
  4. 4repeat i ← i + 1 until a[i] ≥ pivot
  5. 5repeat j ← j − 1 until a[j] ≤ pivot
  6. 6if i < j: swap a[i], a[j]
  7. 7repeat the scans until i ≥ j
  8. 8swap a[lo], a[j]
  9. 9QuickSort(a, lo, j − 1); QuickSort(a, j + 1, hi)
  10. 10end
Quick sort — last element pivot
  1. 1QuickSort(a, lo, hi)
  2. 2if lo < hi
  3. 3pivot ← a[hi]; i ← lo − 1
  4. 4for j ← lo to hi − 1: if a[j] ≤ pivot
  5. 5i ← i + 1; swap a[i], a[j]
  6. 6swap a[i + 1], a[hi]; p ← i + 1
  7. 7QuickSort(a, lo, p − 1); QuickSort(a, p + 1, hi)
  8. 8end

C implementation

quick_sort_first_pivot.ctested ✓ 228/228 cases
C
/* Quick Sort, first element as pivot — KTU PCCST303, Module 4 (lab-record style) */
#include <stdio.h>

void quickSort(int a[], int low, int high)
{
    int pivot, i, j, temp;

    if (low < high) {
        pivot = a[low];                    /* first element is the pivot */
        i = low + 1;
        j = high;
        while (i <= j) {
            while (i <= high && a[i] <= pivot)   /* check i <= high first */
                i++;
            while (a[j] > pivot)                 /* stops at a[low] at worst */
                j--;
            if (i < j) {
                temp = a[i];
                a[i] = a[j];
                a[j] = temp;
            }
        }
        temp = a[low];                     /* put the pivot in its place */
        a[low] = a[j];
        a[j] = temp;
        quickSort(a, low, j - 1);
        quickSort(a, j + 1, high);
    }
}

int main()
{
    int a[100], n, i;

    printf("Enter number of elements: ");
    scanf("%d", &n);
    printf("Enter array elements:\n");
    for (i = 0; i < n; i++)
        scanf("%d", &a[i]);

    quickSort(a, 0, n - 1);

    printf("Sorted array: ");
    for (i = 0; i < n; i++)
        printf("%d ", a[i]);
    printf("\n");
    return 0;
}
Sample input / output · KTU PYQ input · real run, compiled with gcc
Enter number of elements: 10
Enter array elements:
45 36 12 65 24 11 44 54 17 33
Sorted array: 11 12 17 24 33 36 44 45 54 65 

Bold = what you type. Everything else is printed by the program.

quick_sort_last_pivot.ctested ✓ 228/228 cases
C
/* Quick Sort, last element as pivot (Lomuto partition) — KTU PCCST303, Module 4 (lab-record style) */
#include <stdio.h>

int partition(int a[], int low, int high)
{
    int pivot, i, j, temp;

    pivot = a[high];                       /* last element is the pivot */
    i = low - 1;
    for (j = low; j < high; j++) {
        if (a[j] <= pivot) {
            i++;
            temp = a[i];
            a[i] = a[j];
            a[j] = temp;
        }
    }
    temp = a[i + 1];                       /* put the pivot in its place */
    a[i + 1] = a[high];
    a[high] = temp;
    return i + 1;
}

void quickSort(int a[], int low, int high)
{
    int p;

    if (low < high) {
        p = partition(a, low, high);
        quickSort(a, low, p - 1);
        quickSort(a, p + 1, high);
    }
}

int main()
{
    int a[100], n, i;

    printf("Enter number of elements: ");
    scanf("%d", &n);
    printf("Enter array elements:\n");
    for (i = 0; i < n; i++)
        scanf("%d", &a[i]);

    quickSort(a, 0, n - 1);

    printf("Sorted array: ");
    for (i = 0; i < n; i++)
        printf("%d ", a[i]);
    printf("\n");
    return 0;
}
Sample input / output · KTU PYQ input · real run, compiled with gcc
Enter number of elements: 10
Enter array elements:
45 36 12 65 24 11 44 54 17 33
Sorted array: 11 12 17 24 33 36 44 45 54 65 

Bold = what you type. Everything else is printed by the program.

Open in the Code Lab →

Complexity

Space: O(log n) recursion stack on average, O(n) worst case.
CaseWhenRecurrenceTime
Bestpivot splits evenlyT(n) = 2T(n/2) + nO(n log n)
Averagerandom input—O(n log n)
Worstpivot is always min or max (e.g. sorted input with first-element pivot)T(n) = T(n−1) + nO(n²)

Advantages and disadvantages

AdvantagesDisadvantages
Very fast in practice; in-placeWorst case O(n²)
Good cache behaviourNot stable

Edge cases

  • Already sorted input with the first (or last) element as pivot → worst case. Fix: median-of-three or random pivot.
  • All keys equal: Hoare-style scans still split evenly because both pointers stop on equal keys.
  • Textbook code relies on a sentinel a[n] = +∞ so i cannot run off the end; our C version uses the check i ≤ right instead.

Common mistakes

  • Swapping the pivot with a[i] instead of a[j] at the end of the first-element scheme.
  • Forgetting that the pivot is excluded from both recursive calls.
  • Writing O(n log n) as the worst case.

Asked in KTU exams (3)

Quick check — can you get them all?

Question 1

Q1.Worst case of quick sort (first-element pivot) happens on…

Question 2

Q2.Average time of quick sort?

Question 3

Q3.Is quick sort stable?

Practice

Every visualizer has a Practice mode: predict the next state before the animation reveals it. You can also work through the topic's question set on the practice page.

Exam-ready summary

  • Partition → pivot final → recurse on both sides.
  • Best/average O(n log n), worst O(n²); in-place, unstable.
  • State the pivot rule you use.

References

  • Horowitz, Sahni & Anderson-Freed, Fundamentals of Data Structures in C, 2/e — Ch. 7 (Sorting), Ch. 8 (Hashing) §7.3 (Program 7.6)
  • Cormen, Leiserson, Rivest & Stein, Introduction to Algorithms, 3/e — Ch. 2, 6, 7, 8, 11 Ch. 7

Explanations on this page are original. Textbook references point to where the standard treatment can be read; no text is reproduced from them.

Prefer revising from notes? Module-wise notes and question papers on Azhimathi Mayam (opens in a new tab)