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.
Code
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;
}
}
}How the snippet works
Heapsort Build And Extract Max (Java) keeps everything in the class Heapsort and the functions sort and siftDown.
Repetition is confined to for (int i = (n - 2) / 2; i >= 0; i--) siftDown(arr, i, n - 1); — the rest of the file is straight-line.
Applying it
The primary signature is public static void sort(int[] arr)
Statements that matter
for (int end = n - 1; end > 0; end--) { int t = arr[0]; arr[0] = arr[end]; arr[end] = t; siftDown(arr, 0, end - 1); }
if (arr[root] < arr[child]) { int t = arr[root]; arr[root] = arr[child]; arr[child] = t; root = child; } else return;
for (int i = (n - 2) / 2; i >= 0; i--) siftDown(arr, i, n - 1);
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 the runtime need any help from npm, pip, cargo, or the like?
- No — the package manager has nothing to do here; nothing is declared. The file defines `sort`, `siftDown` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.