circlesort.sf 695 B

1234567891011121314151617181920212223242526272829
  1. #!/usr/bin/ruby
  2. #
  3. ## https://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
  4. #
  5. func circlesort(arr, beg=0, end=arr.end) {
  6. var swaps = 0
  7. if (beg < end) {
  8. var (lo, hi) = (beg, end)
  9. do {
  10. if (arr[lo] > arr[hi]) {
  11. arr.swap(lo, hi)
  12. ++swaps
  13. }
  14. ++hi if (--hi == ++lo)
  15. } while (lo < hi)
  16. swaps += circlesort(arr, beg, hi)
  17. swaps += circlesort(arr, lo, end)
  18. }
  19. return swaps
  20. }
  21. var numbers = %n(2 3 3 5 5 1 1 7 7 6 6 4 4 0 0)
  22. do { say numbers } while circlesort(numbers)
  23. var strs = ["John", "Kate", "Zerg", "Alice", "Joe", "Jane", "Alice"]
  24. do { say strs } while circlesort(strs)