Pabl0o0

Untitled

May 17th, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. package kopiec;
  2.  
  3. public class Heap {
  4.  
  5. int left;
  6. int right;
  7. int heap[];
  8. int n;
  9. int smaller;
  10.  
  11. public Heap(int size){
  12. heap = new int[size];
  13. }
  14.  
  15. public void buildingHeap(int[] heap){
  16. n = heap.length-2;
  17. for(int i =n/2; i>=0;i--){
  18. findMinimum(i);
  19. }
  20. }
  21.  
  22. public void findMinimum(int i){
  23. left = 2*i+1;
  24. right = 2*i+2;
  25. if (left<= n+1 && heap[left] < heap[i])
  26. smaller = left;
  27. else
  28. smaller = i;
  29. if (right <= n+1 && heap[right] < heap[i])
  30. if(heap[smaller]>heap[right])
  31. smaller = right;
  32. if (smaller != i){
  33. swap(i,smaller);
  34. findMinimum(smaller);
  35. }
  36. }
  37.  
  38. public void swap(int i, int j){
  39. int tmp = heap[i];
  40. heap[i] = heap[j];
  41. heap[j] = tmp;
  42. }
  43.  
  44. public void heapSort(int [] tab){
  45. heap=tab;
  46. buildingHeap(heap);
  47. for(int i=n+1;i>0;i--){
  48. swap(0,i);
  49. n=n-1;
  50. findMinimum(0);
  51. }
  52. }
  53.  
  54. public void enqueue(int value){
  55. int i=0;
  56. heap=biggerHeap();
  57. i=heap.length-1;
  58. heap[i]=value;
  59.  
  60. while(heap[(i-1)/2]>heap[i]){
  61. int x=heap[(i-1)/2];
  62. heap[(i-1)/2]=heap[i];
  63. heap[i]=x;
  64. i=(i-1)/2;
  65. }
  66. }
  67.  
  68. private int []biggerHeap(){
  69. int []heap1=new int[heap.length+1];
  70. System.arraycopy(heap,0,heap1,0,heap.length);
  71. return heap1;
  72. }
  73.  
  74. public void heapDisplay(){
  75. for(int i=0;i<heap.length;i++)
  76. System.out.print(heap[i]+", ");
  77. System.out.println();
  78. }
  79.  
  80.  
  81. int x = 1;
  82. public int dequeue(){
  83. int tmp = heap[0];
  84. int heapLenght = heap.length-x;
  85. swap(0,heapLenght);
  86. if (heapLenght ==2){
  87. if (heap[1] < heap[0])
  88. swap(0,1);
  89. x++;
  90. return tmp;
  91. }
  92. if (heapLenght == 1)
  93. return tmp;
  94. int i=0;
  95. left = 2*i+1;
  96. right = 2*i+2;
  97.  
  98. while(heap[left]<heap[i] || heap[right]<heap[i]){
  99. if (heap[left] < heap[i])
  100. smaller = left;
  101. else
  102. smaller = i;
  103. if (heap[right] < heap[i])
  104. if(heap[smaller]>heap[right])
  105. smaller = right;
  106. if (smaller != i){
  107. swap(i,smaller);
  108. left = 2*smaller+1;
  109. right = 2*smaller+2;
  110. i = smaller;
  111. }
  112. if (left >= heapLenght || right >= heapLenght){
  113. break;
  114. }
  115. }
  116. x++;
  117. return tmp;
  118. }
  119.  
  120.  
  121.  
  122. }
Advertisement
Add Comment
Please, Sign In to add comment