Skip to content
Laviyx Learn

Try

DS Lab · Experiment 8

Quick sort

CSortingJNTUH R22 · CS306PC

Aim

To write a C program that sorts a list of integers in ascending order using quick sort, showing the array after each partition step.

Algorithm

  1. Read n and the n elements into an array.
  2. Quick sort (low, high): if low < high, partition the part a[low..high] and get the final index p of the pivot. Then quick sort a[low..p-1] and a[p+1..high].
  3. Partition: take the last element a[high] as the pivot. Keep an index i, starting at low - 1, that marks the end of the "smaller than or equal to pivot" part.
  4. For j from low to high - 1: if a[j] <= pivot, increase i and swap a[i] and a[j].
  5. Swap a[i + 1] with a[high]. The pivot is now in its final sorted place, at index i + 1. Return i + 1.
  6. After sorting, print the array.

Program

C
#include <stdio.h>

#define MAX 50

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

void swap(int *x, int *y) {
    int temp = *x;
    *x = *y;
    *y = temp;
}

/* Place the pivot (last element) at its sorted position.
   Smaller or equal elements go to its left, larger ones to its right. */
int partition(int a[], int low, int high) {
    int pivot = a[high];
    int i = low - 1;
    for (int j = low; j < high; j++) {
        if (a[j] <= pivot) {
            i++;
            swap(&a[i], &a[j]);
        }
    }
    swap(&a[i + 1], &a[high]);
    return i + 1;
}

void quick_sort(int a[], int low, int high, int n) {
    if (low < high) {
        int p = partition(a, low, high);
        printf("Pivot %2d placed at index %d: ", a[p], p);
        print_array(a, n);
        quick_sort(a, low, p - 1, n);
        quick_sort(a, p + 1, high, n);
    }
}

int main(void) {
    int a[MAX], n;

    printf("Enter number of elements (1-%d): ", MAX);
    if (scanf("%d", &n) != 1 || n < 1 || n > MAX) {
        printf("Invalid number of elements\n");
        return 1;
    }
    printf("Enter %d elements: ", n);
    for (int i = 0; i < n; i++) {
        if (scanf("%d", &a[i]) != 1) {
            printf("Invalid input\n");
            return 1;
        }
    }

    quick_sort(a, 0, n - 1, n);

    printf("Sorted list: ");
    print_array(a, n);
    return 0;
}

Output

Output
Enter number of elements (1-50): 8
Enter 8 elements: 38 27 43 3 9 82 10 27
Pivot 27 placed at index 4: 27 3 9 10 27 82 38 43 
Pivot 10 placed at index 2: 3 9 10 27 27 82 38 43 
Pivot  9 placed at index 1: 3 9 10 27 27 82 38 43 
Pivot 43 placed at index 6: 3 9 10 27 27 38 43 82 
Sorted list: 3 9 10 27 27 38 43 82 

Recorded by compiling and running this exact program. Typed input appears after each prompt.

How it works

This program uses the last element of each part as the pivot (the Lomuto partition scheme). Many textbooks take the first element as the pivot and move two indexes towards each other (the Hoare scheme); both sort correctly, only the steps differ.

Each "Pivot" line shows the whole array after one partition. The pivot on that line is in its final position and never moves again. Parts with one element or none need no partition, so they print nothing.

Common mistakes

  • Writing the recursive calls as quick_sort(a, low, p, ...). The pivot is already in place, so including it again can make the recursion never shrink. Use p - 1 and p + 1.

  • Using a[j] < pivot in one place and <= in another while copying from different sources. Pick one partition scheme and follow it exactly.

  • Forgetting the final swap of a[i + 1] with the pivot, so the pivot never reaches its sorted place.

  • Calling quick_sort(a, 0, n) instead of quick_sort(a, 0, n - 1), which reads one element past the end of the array.

Viva questions

Try to answer each one aloud before you open it.

  • What is the idea behind quick sort?

    It is a divide and conquer method. It picks a pivot, partitions the array so that smaller elements are on the left of the pivot and larger ones on the right, and then sorts the two parts the same way.

  • What is the time complexity of quick sort?

    O(n log n) on average and in the best case. The worst case is O(n²), which happens when every pivot is the smallest or largest element, for example on an already sorted array when the last element is the pivot.

  • How can the worst case be avoided?

    By choosing the pivot better, for example a random element or the median of the first, middle and last elements.

  • Is quick sort stable? Is it in-place?

    It is not stable, because partitioning can change the order of equal elements. It is in-place, needing only the recursion stack, about O(log n) extra space on average.

  • Why is quick sort often faster than merge sort in practice even though both are O(n log n)?

    It sorts in place without copying into a temporary array, and its inner loop is simple, so it uses the cache well and has smaller constant factors.

Learn the concepts

All Data Structures Lab experiments →