Skip to content

Commit 19b1898

Browse files
authored
odd_even_sort.py (TheAlgorithms#4199)
* odd_even_sort.py * Update odd_even_sort.py * Update odd_even_sort.py
1 parent dcdf390 commit 19b1898

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

sorts/odd_even_sort.py

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
"""For reference
2+
https://en.wikipedia.org/wiki/Odd%E2%80%93even_sort
3+
"""
4+
5+
6+
def odd_even_sort(input_list: list) -> list:
7+
"""this algorithm uses the same idea of bubblesort,
8+
but by first dividing in two phase (odd and even).
9+
Originally developed for use on parallel processors
10+
with local interconnections.
11+
:param collection: mutable ordered sequence of elements
12+
:return: same collection in ascending order
13+
Examples:
14+
>>> odd_even_sort([5 , 4 ,3 ,2 ,1])
15+
[1, 2, 3, 4, 5]
16+
>>> odd_even_sort([])
17+
[]
18+
>>> odd_even_sort([-10 ,-1 ,10 ,2])
19+
[-10, -1, 2, 10]
20+
>>> odd_even_sort([1 ,2 ,3 ,4])
21+
[1, 2, 3, 4]
22+
"""
23+
sorted = False
24+
while sorted is False: # Until all the indices are traversed keep looping
25+
sorted = True
26+
for i in range(0, len(input_list) - 1, 2): # iterating over all even indices
27+
if input_list[i] > input_list[i + 1]:
28+
29+
input_list[i], input_list[i + 1] = input_list[i + 1], input_list[i]
30+
# swapping if elements not in order
31+
sorted = False
32+
33+
for i in range(1, len(input_list) - 1, 2): # iterating over all odd indices
34+
if input_list[i] > input_list[i + 1]:
35+
input_list[i], input_list[i + 1] = input_list[i + 1], input_list[i]
36+
# swapping if elements not in order
37+
sorted = False
38+
return input_list
39+
40+
41+
if __name__ == "__main__":
42+
print("Enter list to be sorted")
43+
input_list = [int(x) for x in input().split()]
44+
# inputing elements of the list in one line
45+
sorted_list = odd_even_sort(input_list)
46+
print("The sorted list is")
47+
print(sorted_list)

0 commit comments

Comments
 (0)