|
| 1 | +# Cycle Sort |
| 2 | +Cycle sort is a comparison sorting algorithm which forces array to be factored into the number of cycles where each of them can be rotated to produce a sorted array. It is theoretically optimal in the sense that it reduces the number of writes to the original array. |
| 3 | + |
| 4 | +## Algorithm |
| 5 | +Consider an array of n distinct elements. An element a is given, index of a can be calculated by counting the number of elements that are smaller than a. |
| 6 | + |
| 7 | +* If the element is found to be at its correct position, simply leave it as it is. |
| 8 | +* Otherwise, find the correct position of a by counting the total number of elements that are less than a. where it must be present in the sorted array. The other element b which is replaced is to be moved to its correct position. This process continues until we got an element at the original position of a. |
| 9 | +* The illustrated process constitutes a cycle. Repeating this cycle for each element of the list. The resulting list will be sorted. |
| 10 | + |
| 11 | +## Pseudo-code |
| 12 | +``` |
| 13 | +
|
| 14 | +Begin |
| 15 | +
|
| 16 | + for start := 0 to n – 2 do |
| 17 | + key := array[start] |
| 18 | + location := start |
| 19 | + for i := start + 1 to n-1 do |
| 20 | + if array[i] < key then |
| 21 | + location:=location +1 |
| 22 | + done |
| 23 | +
|
| 24 | + if location = start then |
| 25 | + ignore lower part, go for next iteration |
| 26 | + while key = array[location] do |
| 27 | + location := location +1 |
| 28 | + done |
| 29 | +
|
| 30 | + if location ≠ start then |
| 31 | + swap array[location] with key |
| 32 | + while location ≠ start do |
| 33 | + location := start |
| 34 | + for i := start + 1 to n-1 do |
| 35 | + if array[i] < key then |
| 36 | + location:=location +1 |
| 37 | + done |
| 38 | +
|
| 39 | + while key = array[location] |
| 40 | + location := location +1 |
| 41 | + if key ≠ array[location] |
| 42 | + swap array[location] and key |
| 43 | + done |
| 44 | + done |
| 45 | +End |
| 46 | +``` |
| 47 | + |
| 48 | +## Complexity |
| 49 | +- Worst case time complexity: `O(n^2)` |
| 50 | +- Average case time complexity: `O(n^2)` |
| 51 | +- Best case time complexity: `O(n^2)` |
| 52 | +- Space complexity: `O(n)` Total, `O(1)` Auxiliary. |
| 53 | + |
| 54 | +## Application |
| 55 | +* This sorting algorithm is best suited for situations where memory write or swap operations are costly. |
| 56 | + |
| 57 | +## Instruction for Running code: |
| 58 | + - C |
| 59 | + ``` |
| 60 | + gcc cycleSort.c |
| 61 | + ./a.out |
| 62 | + ``` |
| 63 | + - Cpp |
| 64 | +
|
| 65 | + ```` |
| 66 | + g++ cycleSort.cpp |
| 67 | + ./a.out |
| 68 | + ```` |
| 69 | +- Java |
| 70 | +
|
| 71 | + ``` |
| 72 | + javac cycleSort.java |
| 73 | + java cycleSort.class |
| 74 | + ``` |
| 75 | +- Python |
| 76 | + ``` |
| 77 | + python3 cycleSort.py |
| 78 | + ``` |
0 commit comments