Advertisement
Dido09

3.4 - HeapSort

May 8th, 2019
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | None | 0 0
  1. public class HeapSort {
  2.  
  3. public void sort(int arr[])
  4. {
  5. int n = arr.length;
  6.  
  7. for (int i = n / 2 - 1; i >= 0; i--)
  8. heapify(arr, n, i);
  9.  
  10. for (int i=n-1; i>=0; i--)
  11. {
  12.  
  13. int temp = arr[0];
  14. arr[0] = arr[i];
  15. arr[i] = temp;
  16.  
  17. heapify(arr, i, 0);
  18. }
  19. }
  20.  
  21. void heapify(int arr[], int n, int i)
  22. {
  23. int largest = i; // Initialize largest as root
  24. int l = 2*i + 1; // left = 2*i + 1
  25. int r = 2*i + 2; // right = 2*i + 2
  26.  
  27. if (l < n && arr[l] > arr[largest])
  28. largest = l;
  29.  
  30. if (r < n && arr[r] > arr[largest])
  31. largest = r;
  32.  
  33. if (largest != i)
  34. {
  35. int swap = arr[i];
  36. arr[i] = arr[largest];
  37. arr[largest] = swap;
  38.  
  39. heapify(arr, n, largest);
  40. }
  41. }
  42. static void printArray(int arr[])
  43. {
  44. int n = arr.length;
  45. for (int i=0; i<n; ++i)
  46. System.out.print(arr[i]+" ");
  47. System.out.println();
  48. }
  49. public static void main(String args[])
  50. {
  51. int arr[] = {12, 11, 13, 5, 6, 7};
  52. int n = arr.length;
  53.  
  54. HeapSort ob = new HeapSort();
  55. ob.sort(arr);
  56.  
  57. System.out.println("Sorted array is");
  58. printArray(arr);
  59. }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement