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.

JavaData Integrity

Code

javasnippet
16 lines
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

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.