Skip to content

odd_even_sort.py #4199

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Feb 11, 2021
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions sorts/odd_even_sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
"""For reference
https://en.wikipedia.org/wiki/Odd%E2%80%93even_sort
"""


def odd_even_sort(input_list):
"""this algorithm uses the same idea of bubblesort,
but by first dividing in two phase (odd and even).
Originally developed for use on parallel processors
with local interconnections.
:param collection: mutable ordered sequence of elements
:return: same collection in ascending order
Examples:
>>> odd_even_sort([5 , 4 ,3 ,2 ,1])
[1, 2, 3, 4, 5]
>>> odd_even_sort([])
[]
>>> odd_even_sort([-10 ,-1 ,10 ,2])
[-10, -1, 2, 10]
>>> odd_even_sort([1 ,2 ,3 ,4])
[1, 2, 3, 4]
"""
sorted = False
while sorted is False: # Until all the indices are traversed keep looping
sorted = True
for i in range(0, len(input_list) - 1, 2): # iterating over all even indices
if input_list[i] > input_list[i + 1]:

input_list[i], input_list[i + 1] = input_list[i + 1], input_list[i]
# swapping if elements not in order
sorted = False

for i in range(1, len(input_list) - 1, 2): # iterating over all odd indices
if input_list[i] > input_list[i + 1]:
input_list[i], input_list[i + 1] = input_list[i + 1], input_list[i]
# swapping if elements not in order
sorted = False
return input_list


if __name__ == "__main__":
print("Enter list to be sorted")
input_list = [int(x) for x in input().split()]
# inputing elements of the list in one line
sorted_list = odd_even_sort(input_list)
print("The sorted list is")
print(sorted_list)