mjain

Heap Sort

Jul 24th, 2019
34
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.38 KB | None | 0 0
  1. public class HeapSort {
  2.     public static void sort(int arr[]) {
  3.         int n = arr.length;
  4.         for (int i = (n / 2) - 1; i >= 0; i--) {
  5.             heapify(arr, n, i);
  6.         }
  7.         System.out.println("After max  heapify");
  8.         print(arr);
  9.  
  10.         for (int i = n - 1; i >= 0; i--) {
  11.             swap(arr, i, 0);
  12.             heapify(arr, i, 0);
  13.         }
  14.         System.out.println();
  15.         System.out.println("After sort");
  16.         print(arr);
  17.     }
  18.  
  19.     public static void print(int[] arr) {
  20.         for (int num : arr) {
  21.             System.out.print(num + " ");
  22.  
  23.         }
  24.     }
  25.  
  26.     public static void heapify(int[] arr, int n, int index) {
  27.         int left = index * 2 + 1;
  28.         int right = index * 2 + 2;
  29.         int largestIndex = index;
  30.         if (left < n && arr[largestIndex] < arr[left]) {
  31.             largestIndex = left;
  32.         }
  33.         if (right < n && arr[largestIndex] < arr[right]) {
  34.             largestIndex = right;
  35.         }
  36.         if (largestIndex != index) {
  37.             swap(arr, index, largestIndex);
  38.             heapify(arr, n, largestIndex);
  39.         }
  40.     }
  41.  
  42.     public static void swap(int[] arr, int i, int j) {
  43.         int temp = arr[i];
  44.         arr[i] = arr[j];
  45.         arr[j] = temp;
  46.     }
  47.  
  48.     public static void main(String[] args) {
  49.         int arr[] = { 12, 11, 13, 5, 6, 7 };
  50.         sort(arr);
  51.     }
  52.  
  53. }
Add Comment
Please, Sign In to add comment