strand_sort.sf 878 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #!/usr/bin/ruby
  2. #
  3. ## https://rosettacode.org/wiki/Sorting_algorithms/Strand_sort
  4. #
  5. func merge(x, y) {
  6. var out = [];
  7. while (x && y) {
  8. given (x[-1] <=> y[-1]) {
  9. when ( 1) { out.prepend(x.pop) }
  10. when (-1) { out.prepend(y.pop) }
  11. default { out.prepend(x.pop, y.pop) }
  12. }
  13. }
  14. x + y + out;
  15. }
  16. func strand(x) {
  17. x || return [];
  18. var out = [x.shift];
  19. if (x.len) {
  20. range(-x.len, -1).each { |i|
  21. if (x[i] >= out[-1]) {
  22. out.append(x.pop_at(i));
  23. }
  24. }
  25. }
  26. return out;
  27. }
  28. func strand_sort(x) {
  29. var out = [];
  30. while (var strd = strand(x)) {
  31. out = merge(out, strd);
  32. }
  33. return out;
  34. }
  35. var numbers = [7,6,5,9,8,4,3,1,2,0];
  36. say strand_sort(numbers);
  37.  
  38. var strs = ["John", "Kate", "Zerg", "Alice", "Joe", "Jane"];
  39. say strand_sort(strs);