heapsort.sf 982 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. #!/usr/bin/ruby
  2. #
  3. ## https://rosettacode.org/wiki/Sorting_algorithms/Heapsort
  4. #
  5. func siftDown(a, start, end) {
  6. var root = start;
  7. while ((2*root + 1) <= end) {
  8. var child = (2*root + 1);
  9. if ((child+1 <= end) && (a[child] < a[child + 1])) {
  10. child += 1;
  11. }
  12. if (a[root] < a[child]) {
  13. a[child, root] = a[root, child];
  14. root = child;
  15. } else {
  16. return();
  17. }
  18. }
  19. }
  20.  
  21. func heapify(a, count) {
  22. var start = ((count - 2) / 2);
  23. while (start >= 0) {
  24. siftDown(a, start, count-1);
  25. start -= 1;
  26. }
  27. }
  28.  
  29. func heapSort(a, count) {
  30. heapify(a, count);
  31. var end = (count - 1);
  32. while (end > 0) {
  33. a[0, end] = a[end, 0];
  34. end -= 1;
  35. siftDown(a, 0, end)
  36. }
  37. return a
  38. }
  39.  
  40. var numbers = [7,6,5,9,8,4,3,1,2,0];
  41. say heapSort(numbers, numbers.len);
  42.  
  43. var strs = ["John", "Kate", "Zerg", "Alice", "Joe", "Jane"];
  44. say heapSort(strs, strs.len);