omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
omega-rosetta / tasks / cycle-sort / oracle.py
| 1 | # Independent reference for "Sorting algorithms/Cycle sort" (Python 3, standard library only). |
| 2 | # expected.txt is this program's stdout; omc never produced it. |
| 3 | def cycle_sort(a): |
| 4 | writes = 0 |
| 5 | for start in range(len(a) - 1): |
| 6 | item = a[start] |
| 7 | pos = start + sum(1 for v in a[start + 1:] if v < item) |
| 8 | if pos == start: |
| 9 | continue |
| 10 | while item == a[pos]: |
| 11 | pos += 1 |
| 12 | a[pos], item = item, a[pos] |
| 13 | writes += 1 |
| 14 | while pos != start: |
| 15 | pos = start + sum(1 for v in a[start + 1:] if v < item) |
| 16 | while item == a[pos]: |
| 17 | pos += 1 |
| 18 | a[pos], item = item, a[pos] |
| 19 | writes += 1 |
| 20 | return writes |
| 21 | a = [5, 0, 1, 2, 2, 3, 5, 1, 1, 0, 5, 6, 9, 8, 0, 1] |
| 22 | print(*a) |
| 23 | w = cycle_sort(a) |
| 24 | assert a == sorted(a) |
| 25 | print(*a) |
| 26 | print("writes:", w) |