Pabl0o0

Untitled

May 17th, 2017
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 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 && heap[left] < heap[i])
  26. smaller = left;
  27. else
  28. smaller = i;
  29. if (right <= n && 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 insert(int value){
  55. int i=0;
  56. if(heap.length==0)
  57. heap=biggerHeap();
  58. heap=biggerHeap();
  59. i=heap.length-1;
  60. heap[i]=value;
  61.  
  62. while(heap[(i-1)/2]>heap[i]){
  63. int x=heap[(i-1)/2];
  64. heap[(i-1)/2]=heap[i];
  65. heap[i]=x;
  66. i=(i-1)/2;
  67. }
  68. }
  69.  
  70. private int []biggerHeap(){
  71. int []heap1=new int[heap.length+1];
  72. System.arraycopy(heap,0,heap1,0,heap.length);
  73. return heap1;
  74. }
  75.  
  76. public void heapDisplay(){
  77. for(int i=0;i<heap.length;i++)
  78. System.out.print(heap[i]+", ");
  79. System.out.println();
  80. }
  81.  
  82.  
  83.  
  84. }
Advertisement
Add Comment
Please, Sign In to add comment