Skip to content

Instantly share code, notes, and snippets.

@maycuatroi1
Created October 26, 2025 22:51
Show Gist options
  • Select an option

  • Save maycuatroi1/4909b61f4a1f6995fab07bd8ab521bb5 to your computer and use it in GitHub Desktop.

Select an option

Save maycuatroi1/4909b61f4a1f6995fab07bd8ab521bb5 to your computer and use it in GitHub Desktop.
public class HeapSort {
public static void heapSort(int[] arr) {
int n = arr.length;
// Build max heap (rearrange array)
for (int i = n / 2 - 1; i >= 0; i--) {
heapify(arr, n, i);
}
// Extract elements from heap one by one
for (int i = n - 1; i > 0; i--) {
// Move current root to end
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
// Call heapify on the reduced heap
heapify(arr, i, 0);
}
}
// To heapify a subtree rooted at node i
// n is size of heap
private static void heapify(int[] arr, int n, int i) {
int largest = i; // Initialize largest as root
int left = 2 * i + 1; // left child
int right = 2 * i + 2; // right child
// If left child is larger than root
if (left < n && arr[left] > arr[largest]) {
largest = left;
}
// If right child is larger than largest so far
if (right < n && arr[right] > arr[largest]) {
largest = right;
}
// If largest is not root
if (largest != i) {
int swap = arr[i];
arr[i] = arr[largest];
arr[largest] = swap;
// Recursively heapify the affected sub-tree
heapify(arr, n, largest);
}
}
public static void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
public static void main(String[] args) {
int[] arr = {64, 25, 12, 22, 11};
System.out.println("Original array:");
printArray(arr);
heapSort(arr);
System.out.println("Sorted array:");
printArray(arr);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment