Advertisement
Guest User

Untitled

a guest
Apr 1st, 2015
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. public class HeapSort {
  2.  
  3. private static int getLeft(int index) {
  4. return index * 2 + 1;
  5. }
  6. private static int getRight(int index) {
  7. return index * 2 + 2;
  8. }
  9. private static void exchange (int[] arr, int first, int second) {
  10.  
  11. int temp = arr[first];
  12. arr[first] = arr[second];
  13. arr[second] = temp;
  14. }
  15. private static void maxHeapify (int[] arr, int size, int index) {
  16.  
  17. int left = getLeft(index);
  18. int right = getRight(index);
  19. int maxIndex = index;
  20.  
  21. if (left < size && arr[left] > arr[maxIndex])
  22. maxIndex = left;
  23.  
  24. if (right < size && arr[right] > arr[maxIndex])
  25. maxIndex = right;
  26.  
  27. if (index != maxIndex) {
  28.  
  29. exchange(arr, index, maxIndex);
  30.  
  31. maxHeapify (arr, size, maxIndex);
  32. }
  33.  
  34. }
  35. private static void buildMaxHeap (int[] arr) {
  36. int size = arr.length;
  37. for (int i = ((size-1) / 2); i >= 0; i --) {
  38. // Do max-heapify on the i.
  39. maxHeapify (arr, size, i);
  40. }
  41. }
  42. public static void heapSort(int[] arr) {
  43. int size = arr.length;
  44.  
  45. buildMaxHeap(arr);
  46.  
  47. for (int i = size - 1; i >= 0; i--) {
  48.  
  49. exchange (arr, 0, i);
  50.  
  51. maxHeapify (arr, i, 0);
  52.  
  53. showArray(arr);
  54.  
  55. }
  56. }
  57.  
  58. public static void showArray (int[] arr) {
  59. int size = arr.length;
  60. for (int i = 0; i < size; i++)
  61. System.out.print(String.format("%-4d", arr[i]));
  62. System.out.println();
  63. }
  64.  
  65.  
  66. public static void main (String[] args) {
  67.  
  68. int[] arr = {53, 42, 86, 11, 27, -5, 89, 0};
  69.  
  70. heapSort(arr);
  71.  
  72. showArray(arr);
  73. }
  74. }
  75.  
  76. /*output:
  77.  
  78. 86 42 53 11 27 -5 0 89
  79. 53 42 0 11 27 -5 86 89
  80. 42 27 0 11 -5 53 86 89
  81. 27 11 0 -5 42 53 86 89
  82. 11 -5 0 27 42 53 86 89
  83. 0 -5 11 27 42 53 86 89
  84. -5 0 11 27 42 53 86 89
  85. -5 0 11 27 42 53 86 89
  86. -5 0 11 27 42 53 86 89
  87.  
  88.  
  89. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement