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.java
class Basic {
public static void main(String[] args) {
int[] arr = new int[] { 4, 1, 5, 2, 3 };
quickSort(arr, 0, arr.length - 1);
printArray(arr);
}
static void printArray(int[] arr) {
System.out.print("[");
for (int i = 0; i < arr.length; i++) {
if (i > 0) System.out.print(", ");
System.out.print(arr[i]);
}
System.out.println("]");
}
static 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;
}
static void quickSort(int[] arr, int low, int high) {
if (low < high) {
int pivotIndex = partition(arr, low, high);
quickSort(arr, low, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, high);
}
}
}
Complexity
- Time: O(n^2) worst, O(n log n) average
- Space: O(log n) average call stack
- Stable: no
Implementation notes
- Java stores the sortable data in one primitive
int[]andquickSortmutates that array in place over inclusivelow/highbounds. Recursion stops whenlow < highis false. partitionchooses the last element,arr[high], as the pivot, initializesi = low - 1, and scansjfromlowwhilej < high.- When
arr[j] <= pivot, the code incrementsiand swapsarr[i]witharr[j]using a local primitiveint tmp; after the scan, it swapsarr[i + 1]with the pivot slot and returnsi + 1. - The replay exposes the first partition states:
1and2move left of pivot3, then the pivot lands at index2before recursive calls cover[1, 2]and[4, 5]. Aside from call-stack frames, the sort uses local primitives and creates no ongoing JVM GC pressure.
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.