Quicksort partitions the input around a pivot and recursively sorts the two sides. This implementation uses the first value as its pivot. Balanced partitions give Θ(n log n) time. Repeatedly choosing an extreme value gives Θ(n²) time, including on already sorted input with this pivot rule.
Simple example
Choose 2 as the pivot. Move 1 to its left and 3 to its right. Each side now has one item.
Start3 1 2
Result1 2 3
Main.java
public class Main {
public static void main(String[] args) {
int[] values = {3, 1, 2};
int pivot = values[2];
int boundary = 0;
int i = 0;
while (i < 2) {
if (values[i] < pivot) {
int saved = values[i];
values[i] = values[boundary];
values[boundary] = saved;
boundary += 1;
}
i += 1;
}
values[2] = values[boundary];
values[boundary] = pivot;
i = 0;
while (i < 3) {
System.out.println(values[i]);
i += 1;
}
}
}
Output
1
2
3
Everyday examples
Divide parcels by a sample weight
Weights are 8, 2 and 5 kilograms. Use 5 as the pivot. What goes on each side?
Start8 2 5
Result2 • 5 • 8
Two is lighter and eight is heavier. The pivot now separates the two groups.
Handle equal book prices
Every book costs 4. What would a three-way partition produce?
Start4 4 4
Result∅ • 4 4 4 • ∅
The equal group contains every book. Neither outer group needs more work.
Notice a poor pivot
Dates 1, 2, 3 and 4 are in order. Always choose the last date. What happens on the first split?
Start1 2 3 4
Result1 2 3 • 4 • ∅
One group still holds three items. Repeating this pattern wastes comparisons.
Cost and limits
Balanced partitions usually lead to O(n log n) work. Repeatedly choosing an extreme pivot can take O(n²).
Time Complexity
Best case: Θ(n log n)
Average case: Θ(n log n)
Worst case: Θ(n²)
Quick Sort Implementation in Java
Java source code
class QuickSortExample {
public void quickSort(int[] arr, int low, int high) {
if(low < high) {
int pivot = partition(arr, low, high);
quickSort(arr, low, pivot - 1);
quickSort(arr, pivot + 1, high);
}
}
private int partition(int[] arr, int low, int high) {
int pivot = arr[low];
int i = low;
int j = high;
while(i < j) {
while(arr[i] <= pivot && i < high) {
i++;
}
while(arr[j] > pivot && j > low) {
j--;
}
if(i < j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
arr[low] = arr[j];
arr[j] = pivot;
return j;
}
public void printArray(int[] arr) {
for(int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("");
}
public static void main(String[] args) {
QuickSortExample obj = new QuickSortExample();
int[] arr = { 15, 3, 12, 6, -9, 9, 0 };
System.out.print("Before Sorting: ");
obj.printArray(arr);
obj.quickSort(arr, 0, arr.length - 1);
System.out.print("After Sorting: ");
obj.printArray(arr);
}
}
Output
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15
Advertisements
Walk through the example
Start with [15, 3, 12, 6, -9, 9, 0].
Use the first value, 15, as the pivot. Scan inward from both ends.
Advance the left index while its value is at most the pivot and the index is below the upper bound. Move the right index left while its value exceeds the pivot.
If the indices have not met, exchange the two misplaced values and continue scanning.
When the indices meet or cross, exchange the first value with the value at the right index. The pivot is now in its final position.
Recursively sort the ranges before and after that position. A range with fewer than two elements is already sorted.
Quick Sort Implementation in Java with explanation
Java source code
class QuickSortExample {
public void quickSort(int[] arr, int low, int high) {
if(low < high) {
// Find the pivot index of the lower bound of an array
int pivot = partition(arr, low, high);
// Apply Divide and conquer strategy
// to sort the left side and right side of an array
// respective to the pivot position
// Left hand side array
quickSort(arr, low, pivot - 1);
// Right hand side array
quickSort(arr, pivot + 1, high);
}
}
private int partition(int[] arr, int low, int high) {
// Pick a lowest bound element as an pivot value
int pivot = arr[low];
int i = low;
int j = high;
while(i < j) {
// Increment the index value of "i"
// till the left most values should be less than or equal to the pivot value
while(arr[i] <= pivot && i < high) {
i++;
}
// Decrement the index value of "j"
// till the right most values should be greater than to the pivot value
while(arr[j] > pivot && j > low) {
j--;
}
// Interchange the values of present
// in the index i and j of an array only if i is less than j
if(i < j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
// Interchange the element in j's poisition to the lower bound of an array
// and place the Pivot element to the j's position
arr[low] = arr[j];
arr[j] = pivot;
// Finally return the appropriate index position of the pivot element
return j;
}
public void printArray(int[] arr) {
// Loop the item and print each item in the console with white space seperated
for(int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("");
}
public static void main(String[] args) {
QuickSortExample obj = new QuickSortExample();
int[] arr = { 15, 3, 12, 6, -9, 9, 0 };
System.out.print("Before Sorting: ");
obj.printArray(arr);
obj.quickSort(arr, 0, arr.length - 1);
System.out.print("After Sorting: ");
obj.printArray(arr);
}
}
Output
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15