Heapsort Build And Extract Max (Java)

Sort a Java array by building a max heap in place then repeatedly extracting the maximum to the end.

JavaData Integrity

Code

snippet
public class Heapsort {
    public static void sort(int[] arr) {
        int n = arr.length;
        for (int i = (n - 2) / 2; i >= 0; i--) siftDown(arr, i, n - 1);
        for (int end = n - 1; end > 0; end--) { int t = arr[0]; arr[0] = arr[end]; arr[end] = t; siftDown(arr, 0, end - 1); }
    }
    static void siftDown(int[] arr, int start, int end) {
        int root = start;
        while (root * 2 + 1 <= end) {
            int child = root * 2 + 1;
            if (child + 1 <= end && arr[child] < arr[child + 1]) child++;
            if (arr[root] < arr[child]) { int t = arr[root]; arr[root] = arr[child]; arr[child] = t; root = child; } else return;
        }
    }
}