Advertisement
lashrone1

gavno

Dec 1st, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.44 KB | None | 0 0
  1. import java.util.Arrays;
  2.  
  3. class MaxHeap {
  4. private int[] Heap;
  5. private int size;
  6. private int maxsize;
  7.  
  8.  
  9. public MaxHeap(int maxsize) {
  10. this.maxsize = maxsize;
  11. this.size = 0;
  12. Heap = new int[this.maxsize + 1];
  13. Heap[0] = Integer.MAX_VALUE;
  14. }
  15.  
  16.  
  17. private int parent(int pos) {
  18. return pos / 2;
  19. }
  20.  
  21.  
  22. private int leftChild(int pos) {
  23. return (2 * pos);
  24. }
  25.  
  26. private int rightChild(int pos) {
  27. return (2 * pos) + 1;
  28. }
  29.  
  30.  
  31. private boolean isLeaf(int pos) {
  32. if (pos >= (size / 2) && pos <= size) {
  33. return true;
  34. }
  35. return false;
  36. }
  37.  
  38. private void swap(int fpos, int spos) {
  39. int tmp;
  40. tmp = Heap[fpos];
  41. Heap[fpos] = Heap[spos];
  42. Heap[spos] = tmp;
  43. }
  44.  
  45.  
  46. private void maxHeapify(int pos) {
  47. if (isLeaf(pos))
  48. return;
  49.  
  50. if (Heap[pos] < Heap[leftChild(pos)] ||
  51. Heap[pos] < Heap[rightChild(pos)]) {
  52.  
  53. if (Heap[leftChild(pos)] > Heap[rightChild(pos)]) {
  54. swap(pos, leftChild(pos));
  55. maxHeapify(leftChild(pos));
  56. } else {
  57. swap(pos, rightChild(pos));
  58. maxHeapify(rightChild(pos));
  59. }
  60. }
  61. }
  62.  
  63.  
  64. public void insert(int element) {
  65. Heap[++size] = element;
  66.  
  67. int current = size;
  68. while (Heap[current] > Heap[parent(current)]) {
  69. swap(current, parent(current));
  70. current = parent(current);
  71. }
  72. }
  73.  
  74. public void print() {
  75. for (int i = 1; i <= size / 2; i++) {
  76. System.out.print(" PARENT : " + Heap[i] + " LEFT CHILD : " +
  77. Heap[2 * i] + " RIGHT CHILD :" + Heap[2 * i + 1]);
  78. System.out.println();
  79. }
  80. }
  81.  
  82.  
  83. // Remove an element from max heap
  84. public int extractMax() {
  85. int popped = Heap[1];
  86. Heap[1] = Heap[size--];
  87. maxHeapify(1);
  88. return popped;
  89. }
  90.  
  91. }
  92. class Main{
  93. public static void main(String[] arg)
  94. {
  95. System.out.println("The Max Heap is ");
  96. MaxHeap maxHeap = new MaxHeap(15);
  97.  
  98. for(int i = 0;i<10;i++){
  99. int b = 0 + (int)(Math.random()*99);
  100. maxHeap.insert(b);
  101. }
  102.  
  103.  
  104. maxHeap.print();
  105. System.out.println("The max val is " + maxHeap.extractMax());
  106. }
  107. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement