Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class HeapSort {
- public static void sort(int arr[]) {
- int n = arr.length;
- for (int i = (n / 2) - 1; i >= 0; i--) {
- heapify(arr, n, i);
- }
- System.out.println("After max heapify");
- print(arr);
- for (int i = n - 1; i >= 0; i--) {
- swap(arr, i, 0);
- heapify(arr, i, 0);
- }
- System.out.println();
- System.out.println("After sort");
- print(arr);
- }
- public static void print(int[] arr) {
- for (int num : arr) {
- System.out.print(num + " ");
- }
- }
- public static void heapify(int[] arr, int n, int index) {
- int left = index * 2 + 1;
- int right = index * 2 + 2;
- int largestIndex = index;
- if (left < n && arr[largestIndex] < arr[left]) {
- largestIndex = left;
- }
- if (right < n && arr[largestIndex] < arr[right]) {
- largestIndex = right;
- }
- if (largestIndex != index) {
- swap(arr, index, largestIndex);
- heapify(arr, n, largestIndex);
- }
- }
- public static void swap(int[] arr, int i, int j) {
- int temp = arr[i];
- arr[i] = arr[j];
- arr[j] = temp;
- }
- public static void main(String[] args) {
- int arr[] = { 12, 11, 13, 5, 6, 7 };
- sort(arr);
- }
- }
Add Comment
Please, Sign In to add comment