FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
algorithms-python/algorithms/sort/cycle_sort.py at master · Mu-L/algorithms-python · GitHub
Mu-L
/
algorithms-python
Public
forked from
keon/algorithms
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
algorithms-python
/
algorithms
/
sort
/
cycle_sort.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
46 lines (38 loc) · 1.33 KB
Breadcrumbs
algorithms-python
/
algorithms
/
sort
/
cycle_sort.py
Copy path
File metadata and controls
46 lines (38 loc) · 1.33 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
Back
|
FazBrowse Home
|
New Git URL