Advertisement
Guest User

Untitled

a guest
Apr 19th, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.02 KB | None | 0 0
  1.  
  2. public static int[] HeapSort(int[] tab){
  3.  
  4. buildMaxHeap(tab);
  5.  
  6. return tab;
  7. }
  8.  
  9. private static void buildMaxHeap(int[] tab)
  10. {
  11.  
  12.  
  13. for(int i=tab.length-1; i >= 0; i--)
  14. {
  15. heapify(tab, 0, i);
  16.  
  17. int x = tab[i];
  18. tab[i] = tab[0];
  19. tab[0] = x;
  20. }
  21. }
  22. private static void heapify(int[] tab, int index, int maxIndex)
  23. {
  24. int indexOfLeft = 2 * index + 1;
  25. int indexOfRight = 2 * index + 2;
  26. int pomI = index+1;
  27.  
  28. if(indexOfRight <= maxIndex) heapify(tab, pomI, maxIndex);
  29.  
  30. if(indexOfRight <= maxIndex && tab[index] < tab[indexOfRight])
  31. {
  32. int x = tab[indexOfRight];
  33. tab[indexOfRight] = tab[index];
  34. tab[index] = x;
  35. }
  36.  
  37. if(indexOfLeft <= maxIndex && tab[index] < tab[indexOfLeft])
  38. {
  39. int x = tab[indexOfLeft];
  40. tab[indexOfLeft] = tab[index];
  41. tab[index] = x;
  42. }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement