Quicksort With Median Of Three Pivot (Java)
Sort a Java array in place using quicksort with median-of-three pivot selection to avoid worst-case behavior.
Code
public class Quicksort {
public static void sort(int[] arr, int lo, int hi) {
if (lo >= hi) return;
int mid = (lo + hi) >>> 1;
if (arr[mid] < arr[lo]) swap(arr, lo, mid);
if (arr[hi] < arr[lo]) swap(arr, lo, hi);
if (arr[mid] < arr[hi]) swap(arr, hi, mid);
int pivot = arr[hi];
int i = lo;
for (int j = lo; j < hi; j++) if (arr[j] < pivot) swap(arr, i++, j);
swap(arr, i, hi);
sort(arr, lo, i - 1);
sort(arr, i + 1, hi);
}
static void swap(int[] a, int i, int j) { int t = a[i]; a[i] = a[j]; a[j] = t; }
}What the code does
Quicksort With Median Of Three Pivot (Java) keeps everything in the class Quicksort and the functions sort and swap.
Repetition is confined to for (int j = lo; j < hi; j++) if (arr[j] < pivot) swap(arr, i++, j); — the rest of the file is straight-line.
Applying it
The main signature reads public static void sort(int[] arr, int lo, int hi)
Statements that matter
static void swap(int[] a, int i, int j) { int t = a[i]; a[i] = a[j]; a[j] = t; }
for (int j = lo; j < hi; j++) if (arr[j] < pivot) swap(arr, i++, j);
if (arr[mid] < arr[lo]) swap(arr, lo, mid);
Interactive Tools for This Topic
JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.SemVer SorterParse and sort Semantic Version 2.0.0 strings with prerelease and build metadata, respecting prerelease-below-release precedence.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Does this work in a bare project with no dependencies file?
- Yes — a bare project runs it as-is, since nothing needs declaring. The file defines `sort`, `swap` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.