Sorting
Quick Sort (Lomuto)
Choose the last item as a pivot, partition smaller values to its left, then recurse on the two sides.
Algorithm
Basic Implementation
basic.c
#include <stdio.h>
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; ++j) {
if (arr[j] <= pivot) {
++i;
int tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp;
}
}
int tmp = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = tmp;
return i + 1;
}
void quick_sort(int arr[], int low, int high) {
if (low < high) {
int pivot_index = partition(arr, low, high);
quick_sort(arr, low, pivot_index - 1);
quick_sort(arr, pivot_index + 1, high);
}
}
int main(void) {
int arr[] = {4, 1, 5, 2, 3};
int n = 5;
quick_sort(arr, 0, n - 1);
printf("[");
for (int i = 0; i < n; ++i) {
if (i > 0) printf(", ");
printf("%d", arr[i]);
}
printf("]\n");
return 0;
}
Complexity
- Time: O(n^2) worst, O(n log n) average
- Space: O(log n) average call stack
- Stable: no
Implementation notes
- C stores
int arr[] = {4, 1, 5, 2, 3}as a fixed local array inmain, then callsquick_sort(arr, 0, n - 1)withint n = 5. quick_sort(int arr[], int low, int high)andpartition(int arr[], int low, int high)receive the array as a pointer after parameter decay, so all swaps mutate the original stack array.- Lomuto partition uses
pivot = arr[high],i = low - 1, andjscanning fromlowtohigh - 1; this checked input starts with pivot3. - Swaps are manual three-assignment exchanges through a stack
int tmp: first forarr[i]/arr[j]whenarr[j] <= pivot, then forarr[i + 1]andarr[high]to place the pivot. - The trace records
[4, 1, 5, 2, 3], keeps4, swaps1left to[1, 4, 5, 2, 3], keeps5, swaps2left to[1, 2, 5, 4, 3], then swaps pivot3into index2for[1, 2, 3, 4, 5]. - Recursion runs only when
low < high; the replay summarizes the left[1, 2]and right[4, 5]calls and does not include a separate worst-case trace. - Output is formatted manually with
printf("["), comma-separatedprintf("%d", arr[i]), andprintf("]\n"). Visible memory is stack frames and scalar temporaries; there is no heap allocation.
pivot
The final element is moved to the boundary between smaller and larger values.
partition
One scan rearranges the current range before the recursive calls.