Advertisement
Guest User

Untitled

a guest
Mar 25th, 2017
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. public class Heap {
  2.  
  3. public static int[] array = new int[10];
  4. public static int heapSize = 10;
  5.  
  6. public static void main(String[] args) {
  7.  
  8. array[0] = 4;
  9. array[1] = 1;
  10. array[2] = 3;
  11. array[3] = 2;
  12. array[4] = 16;
  13. array[5] = 9;
  14. array[6] = 10;
  15. array[7] = 14;
  16. array[8] = 8;
  17. array[9] = 7;
  18.  
  19. long startingTime = System.nanoTime();
  20. SortHeapAssending();
  21. long endingTime = System.nanoTime();
  22.  
  23. heapSize = 10;
  24. for (int j = 0; j < heapSize; j++) {
  25. System.out.println(array[j]);
  26. }
  27.  
  28. System.out.println("Heap Execution Time " + (endingTime - startingTime) + " nano seconds");
  29. }
  30.  
  31. public static void SortHeapAssending()
  32. {
  33. BuildMaxHeap(array);
  34.  
  35. for (int i = (heapSize-1); i>=1; i--)
  36. {
  37. Swap(array,0,i);
  38. heapSize = heapSize - 1;
  39. MaxHeapify(array,0);
  40. }
  41. }
  42.  
  43. public static void BuildMaxHeap(int[] array)
  44. {
  45. for (int i = (heapSize-1)/2; i >= 0; i--)
  46. {
  47. MaxHeapify(array, i);
  48. }
  49. }
  50. public static void MaxHeapify(int[] array, int i)
  51. {
  52. int largestIndex;
  53. int leftIndex = 2 * i + 1;
  54. int rightIndex = 2 * i + 2;
  55. if (leftIndex <= heapSize-1 && array[leftIndex] > array[i])
  56. {
  57. largestIndex = leftIndex;
  58. }
  59. else
  60. {
  61. largestIndex = i;
  62. }
  63. if (rightIndex <= heapSize-1 && array[rightIndex] > array[largestIndex])
  64. {
  65. largestIndex = rightIndex;
  66. }
  67. if (largestIndex != i)
  68. {
  69. Swap(array,i,largestIndex);
  70. MaxHeapify(array, largestIndex);
  71. }
  72. }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement