Quicksort in C: solved exercise with Lomuto partition

  2 minutes

If you searched for quicksort in C solved exercise, this example implements the classic Lomuto partition version.

Sort an integer array using quicksort and print the final order.

#include <stdio.h>

int partition(int a[], int l, int r) {
    int piv = a[r];
    int i = l - 1;

    for (int j = l; j < r; j++) {
        if (a[j] <= piv) {
            i++;
            int tmp = a[i]; a[i] = a[j]; a[j] = tmp;
        }
    }

    int tmp = a[i + 1]; a[i + 1] = a[r]; a[r] = tmp;
    return i + 1;
}

void quicksort(int a[], int l, int r) {
    if (l < r) {
        int p = partition(a, l, r);
        quicksort(a, l, p - 1);
        quicksort(a, p + 1, r);
    }
}

int main(void) {
    int a[] = {10, 7, 8, 9, 1, 5};
    int n = sizeof(a) / sizeof(a[0]);

    quicksort(a, 0, n - 1);
    for (int i = 0; i < n; i++) printf("%d ", a[i]);
    printf("\n");
    return 0;
}
1 5 7 8 9 10
  • Average: O(n log n)
  • Worst case: O(n^2)
  • Wrong recursion bounds (p - 1, p + 1).
  • Ignoring pivot behavior on nearly sorted input.
  • Mixing Lomuto with Hoare partition logic.

Quicksort ideas appear in ranking engines and preprocessing for fast lookup workflows.

If you want a complete path with progressive difficulty:

Yes. It targets patterns that commonly appear in practice assignments, technical interviews, and C programming exams.

In Programming in C in 100 Solved Exercises and C Exercises. Kindle Unlimited: View on Amazon.

Start with small inputs, run edge cases (empty, one item, max capacity), then rewrite the solution from scratch without copying.