forked from nryoung/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgnome_sort.py
More file actions
39 lines (29 loc) · 828 Bytes
/
gnome_sort.py
File metadata and controls
39 lines (29 loc) · 828 Bytes
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
"""
gnome_sort.py
Implementation of gnome sort on a list and returns a sorted list.
Gnome Sort Overview:
---------------------
A sorting algorithm similar to insertion sort except that the element is moved to its proper place by a series of swaps.
Time Complexity: O(n^2)
Space Complexity: O(1) auxillary
Stable: No
Psuedo code: http://en.wikipedia.org/wiki/Gnome_sort
"""
def sort(seq):
i = 1
last = 0
while i < len(seq):
if seq[i] < seq[i-1]:
seq[i], seq[i-1] = seq[i-1], seq[i]
if i > 1:
if last == 0:
last = i
i -= 1
else:
i += 1
else:
if last != 0:
i = last
last = 0
i += 1
return seq