Skip to content

Commit c811d73

Browse files
feat: add cycle sort (#212)
* Feat: add cycle sort * remove redundant links * chore: apply suggestions from code review --------- Co-authored-by: David Leal <[email protected]>
1 parent d013940 commit c811d73

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

Diff for: en/Sorting Algorithms/Cycle Sort.md

+69
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
# Cycle Sort
2+
3+
#### Problem Statement
4+
5+
Given an unsorted array of n elements, write a function to sort the array
6+
7+
#### Approach
8+
9+
- If the element is already at its correct position do nothing
10+
- Otherwise, find the correct position of a by counting the total number of elements that are less than current element
11+
- Insert current element into its correct position
12+
- Set replaced element as new current element and find its correct position
13+
- Continue process until array is sorted
14+
15+
#### Time Complexity
16+
17+
`O(n^2)` Worst case performance
18+
19+
`O(n^2)` Best-case performance
20+
21+
`O(n^2)` Average performance
22+
23+
#### Space Complexity
24+
25+
`O(n)` Worst case
26+
27+
#### Application of algorithm
28+
29+
- Cycle sort algorithm is useful for situations where memory write or element swap operations are costly.
30+
31+
#### Example
32+
33+
A single cycle of sorting array | b | d | e | a | c |
34+
35+
```
36+
1. Select element for which the cycle is run, i.e. "b".
37+
38+
|b|d|e|a|c|
39+
40+
b - current element
41+
42+
2. Find correct location for current element and update current element.
43+
44+
|b|b|e|a|c|
45+
46+
d - current element
47+
48+
3. One more time, find correct location for current element and update current element.
49+
50+
|b|b|e|d|c|
51+
52+
a - current element
53+
54+
4. Current element is inserted into position of initial element "b" which ends the cycle.
55+
56+
|a|b|e|d|c|
57+
58+
a - current element
59+
60+
5. New cycle should be started for next element.
61+
```
62+
63+
#### Video Explanation
64+
65+
[A video explaining the Cycle Sort Algorithm](https://www.youtube.com/watch?v=gZNOM_yMdSQ)
66+
67+
#### The Algorithms Page
68+
69+
[Cycle Sort](https://the-algorithms.com/algorithm/cycle-sort)

0 commit comments

Comments
 (0)