Guest User

Untitled

a guest
Feb 19th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.21 KB | None | 0 0
  1.  
  2. /**
  3. * Heapsort (method) is a comparison-based sorting algorithm,
  4. * and is part of the selection sort family. Although somewhat
  5. * slower in practice on most machines than a good implementation of
  6. * quicksort, it has the advantage of a worst-case Θ(n log n) runtime.
  7. * Heapsort is an in-place algorithm, but is not a stable sort.
  8. *
  9. * @author ishikawa
  10. *
  11. */
  12. public class Heapsort {
  13. private static void swap(int[] elements, int i, int j) {
  14. int tmp = elements[j];
  15. elements[j] = elements[i];
  16. elements[i] = tmp;
  17. }
  18.  
  19. private static void shiftup(int[] elements, int n) {
  20. int i = n;
  21. while (i > 0) {
  22. final int p = (i+1)/2-1;
  23. if (elements[i] < elements[p]) break;
  24. swap(elements, i, p);
  25. i = p;
  26. }
  27. }
  28.  
  29. private static void shiftdown(int[] elements, int n) {
  30. int i = 0;
  31. while(i <= n) {
  32. int c = (i+1)*2-1; // left child
  33. if (c > n) break;
  34. if ((c+1) <= n && elements[c+1] > elements[c]) c++;
  35. if (elements[i] >= elements[c]) break;
  36. swap(elements, i, c);
  37. i = c;
  38. }
  39. }
  40.  
  41. public static void sort(int[] a) {
  42. for (int i = 1; i < a.length; i++) shiftup(a, i);
  43. for (int i = a.length - 1; i > 0; i--) {
  44. swap(a, 0, i);
  45. shiftdown(a, i-1);
  46. }
  47. }
  48.  
  49.  
  50. }
Add Comment
Please, Sign In to add comment