Created
January 19, 2022 19:53
-
-
Save senoritadeveloper01/c30c19069ddc8d056939a419ee774e32 to your computer and use it in GitHub Desktop.
Heap Sort Implementation in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static void heapSort(int arr[]) { | |
for (int i = arr.length / 2 - 1; i >= 0; i--) { | |
heapify(arr, i); | |
} | |
for (int i = arr.length - 1; i >= 0; i--) { | |
int temp = arr[0]; | |
arr[0] = arr[i]; | |
arr[i] = temp; | |
heapify(arr, i, 0); | |
} | |
} | |
private static void heapify(int arr[], int i) { | |
int largest = i; | |
int left = 2 * i + 1; | |
int right = 2 * i + 2; | |
if (left < arr.length && arr[left] > arr[largest]) | |
largest = left; | |
if (right < arr.length && arr[right] > arr[largest]) | |
largest = right; | |
if (largest != i) { | |
int temp = arr[i]; | |
arr[i] = arr[largest]; | |
arr[largest] = temp; | |
heapify(arr, largest); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment