java 39 lines · 7 steps

Quicksort with Lomuto partitioning in Java

A recursive in-place sort that partitions around a pivot and conquers each half.

Explained by highlit
1public final class Quicksort {
2 
3 private Quicksort() {
4 }
5 
6 public static void sort(int[] array) {
7 if (array == null || array.length < 2) {
8 return;
9 }
10 quicksort(array, 0, array.length - 1);
11 }
12 
13 private static void quicksort(int[] array, int low, int high) {
14 if (low < high) {
15 int pivotIndex = partition(array, low, high);
16 quicksort(array, low, pivotIndex - 1);
17 quicksort(array, pivotIndex + 1, high);
18 }
19 }
20 
21 private static int partition(int[] array, int low, int high) {
22 int pivot = array[high];
23 int i = low - 1;
24 for (int j = low; j < high; j++) {
25 if (array[j] <= pivot) {
26 i++;
27 swap(array, i, j);
28 }
29 }
30 swap(array, i + 1, high);
31 return i + 1;
32 }
33 
34 private static void swap(int[] array, int a, int b) {
35 int temp = array[a];
36 array[a] = array[b];
37 array[b] = temp;
38 }
39}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Quicksort sorts in place by recursively partitioning subranges around a chosen pivot.
  2. 2The Lomuto scheme keeps everything ≤ the pivot to the left, then drops the pivot into its final slot.
  3. 3Guarding the public entry point against null and tiny arrays keeps the recursive core simple.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Quicksort with Lomuto partitioning in Java — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code