Advertisement
Guest User

Untitled

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