forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cycle_sort.py
46 lines (38 loc) · 1.33 KB
/
cycle_sort.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
def cycle_sort(arr):
"""
cycle_sort
This is based on the idea that the permutations to be sorted
can be decomposed into cycles,
and the results can be individually sorted by cycling.
reference: https://en.wikipedia.org/wiki/Cycle_sort
Average time complexity : O(N^2)
Worst case time complexity : O(N^2)
"""
len_arr = len(arr)
# Finding cycle to rotate.
for cur in range(len_arr - 1):
item = arr[cur]
# Finding an indx to put items in.
index = cur
for i in range(cur + 1, len_arr):
if arr[i] < item:
index += 1
# Case of there is not a cycle
if index == cur:
continue
# Putting the item immediately right after the duplicate item or on the right.
while item == arr[index]:
index += 1
arr[index], item = item, arr[index]
# Rotating the remaining cycle.
while index != cur:
# Finding where to put the item.
index = cur
for i in range(cur + 1, len_arr):
if arr[i] < item:
index += 1
# After item is duplicated, put it in place or put it there.
while item == arr[index]:
index += 1
arr[index], item = item, arr[index]
return arr