Quicksort in C: solved exercise
If you searched for quicksort in C solved exercise, this example implements the classic Lomuto partition version.
Problem statement
Sort an integer array using quicksort and print the final order.
C solution
#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;
}Expected output
1 5 7 8 9 10Complexity
- Average: O(n log n)
- Worst case: O(n^2)
Common mistakes
- Wrong recursion bounds (
p - 1,p + 1). - Ignoring pivot behavior on nearly sorted input.
- Mixing Lomuto with Hoare partition logic.
Practical use
Quicksort ideas appear in ranking engines and preprocessing for fast lookup workflows.
Recommended next exercise
- Merge sort in C: solved exercise with divide and conquer
- Binary search in C: solved exercise on sorted arrays
- Binary tree in C: solved insertion and search exercise
- All C exercises
Guided practice and full book
If you want a complete path with progressive difficulty:
FAQ
Is this exercise useful for C exams and technical interviews?
Yes. It targets patterns that commonly appear in practice assignments, technical interviews, and C programming exams.
Where can I keep practicing with more solved C exercises?
In Programming in C in 100 Solved Exercises and C Exercises. Kindle Unlimited: View on Amazon.
How should I practice this exercise type to improve faster?
Start with small inputs, run edge cases (empty, one item, max capacity), then rewrite the solution from scratch without copying.