Advertisement
Guest User

Untitled

a guest
Jun 26th, 2019
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.49 KB | None | 0 0
  1. public class minHeap {
  2. public int capacity;
  3. public int [] mH;
  4. public int currentSize;
  5. public minHeap(int capacity){
  6. this.capacity=capacity;
  7. mH = new int [capacity+1];
  8. currentSize =0;
  9. }
  10. public void createHeap(int [] arrA){
  11. if(arrA.length>0){
  12. for(int i=0;i<arrA.length;i++){
  13. insert(arrA[i]);
  14. }
  15. }
  16. }
  17. public void display(){
  18. for(int i=1;i<mH.length;i++){
  19. System.out.print(" " + mH[i]);
  20. }
  21. System.out.println("");
  22. }
  23. public void insert(int x) {
  24. if(currentSize==capacity){
  25. System.out.println("heap is full");
  26. return;
  27. }
  28. currentSize++;
  29. int idx = currentSize;
  30. mH[idx] = x;
  31. bubbleUp(idx);
  32. }
  33.  
  34. public void bubbleUp(int pos) {
  35. int parentIdx = pos/2;
  36. int currentIdx = pos;
  37. while (currentIdx > 0 && mH[parentIdx] > mH[currentIdx]) {
  38.  
  39. swap(currentIdx,parentIdx);
  40. currentIdx = parentIdx;
  41. parentIdx = parentIdx/2;
  42. }
  43. }
  44.  
  45. public int extractMin() {
  46. int min = mH[1];
  47. mH[1] = mH[currentSize];
  48. mH[currentSize] = 0;
  49. sinkDown(1);
  50. currentSize--;
  51. return min;
  52. }
  53.  
  54. public void sinkDown(int k) {
  55. int smallest = k;
  56. int leftChildIdx = 2 * k;
  57. int rightChildIdx = 2 * k+1;
  58. if (leftChildIdx < heapSize() && mH[smallest] > mH[leftChildIdx]) {
  59. smallest = leftChildIdx;
  60. }
  61. if (rightChildIdx < heapSize() && mH[smallest] > mH[rightChildIdx]) {
  62. smallest = rightChildIdx;
  63. }
  64. if (smallest != k) {
  65.  
  66. swap(k, smallest);
  67. sinkDown(smallest);
  68. }
  69. }
  70.  
  71. public void swap(int a, int b) {
  72. int temp = mH[a];
  73. mH[a] = mH[b];
  74. mH[b] = temp;
  75. }
  76. public boolean isEmpty() {
  77. return currentSize == 0;
  78. }
  79.  
  80. public int heapSize(){
  81. return currentSize;
  82. }
  83.  
  84. public static void main(String args[]){
  85. int arrA [] = {3,2,1,7,8,4,10,16,12};
  86. System.out.print("Original Array : ");
  87. for(int i=0;i<arrA.length;i++){
  88. System.out.print(" " + arrA[i]);
  89. }
  90. minHeap m = new minHeap(arrA.length);
  91. System.out.print("\nMin-Heap : ");
  92. m.createHeap(arrA);
  93. m.display();
  94. System.out.print("Extract Min :");
  95. for(int i=0;i<arrA.length;i++){
  96. System.out.print(" " + m.extractMin());
  97. }
  98. }
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement