|
| 1 | + |
| 2 | +def less_count(arr, i, target): |
| 3 | + """ |
| 4 | + Returns the no. of elements less than the target. |
| 5 | + """ |
| 6 | + |
| 7 | + count = 0 |
| 8 | + |
| 9 | + for j in range(i, len(arr)): |
| 10 | + |
| 11 | + if arr[j] < target: |
| 12 | + count += 1 |
| 13 | + |
| 14 | + return count |
| 15 | + |
| 16 | +def cyclesort(arr, n): |
| 17 | + """ |
| 18 | + Cycle sorting on the given array/list. |
| 19 | +
|
| 20 | + Time Complexity: O(n^2) |
| 21 | + """ |
| 22 | + |
| 23 | + i = 0 |
| 24 | + |
| 25 | + while i < n: |
| 26 | + |
| 27 | + # Get the current element. |
| 28 | + element = arr[i] |
| 29 | + |
| 30 | + # Get the number of elements less than the current element. |
| 31 | + count = less_count(arr, i + 1, element) |
| 32 | + |
| 33 | + # Swap the current element in it's final sorted position if there are |
| 34 | + # elements less than the current element. Otherwise, move to the next |
| 35 | + # element. |
| 36 | + if count > 0: |
| 37 | + |
| 38 | + arr[i + count], arr[i] = arr[i], arr[i + count] |
| 39 | + else: |
| 40 | + |
| 41 | + i += 1 |
| 42 | + |
| 43 | + |
| 44 | + |
| 45 | +if __name__ == '__main__': |
| 46 | + |
| 47 | + arr = [2, 6, 4, 3, 1, 5] |
| 48 | + |
| 49 | + print('Before Sorting:', arr) |
| 50 | + cyclesort(arr, len(arr)) |
| 51 | + print('After Sorting:', arr) |
| 52 | + |
| 53 | +# Result: |
| 54 | +# --- |
| 55 | +# |
| 56 | +# Before Sorting: [2, 6, 4, 3, 1, 5] |
| 57 | +# After Sorting: [1, 2, 3, 4, 5, 6] |
| 58 | + |
0 commit comments