Pabl0o0

Untitled

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