This is basically a variation of bubble-sort. This algorithm is divided into two phases- Odd and Even Phase. The algorithm runs until the array elements are sorted and in each iteration two phases occurs- Odd and Even Phases.
In the odd phase, we perform a bubble sort on odd indexed elements and in the even phase, we perform a bubble sort on even indexed elements.
Python3
def oddEvenSort(arr, n):
isSorted = 0
while isSorted = = 0 :
isSorted = 1
temp = 0
for i in range ( 1 , n - 1 , 2 ):
if arr[i] > arr[i + 1 ]:
arr[i], arr[i + 1 ] = arr[i + 1 ], arr[i]
isSorted = 0
for i in range ( 0 , n - 1 , 2 ):
if arr[i] > arr[i + 1 ]:
arr[i], arr[i + 1 ] = arr[i + 1 ], arr[i]
isSorted = 0
return
arr = [ 34 , 2 , 10 , - 9 ]
n = len (arr)
oddEvenSort(arr, n);
for i in range ( 0 , n):
print (arr[i], end = " " )
|
Time Complexity: O(n2)
Auxiliary Space: O(1)
Python Program for Odd-Even Sort / Brick Sort Using the sorted() function
In this method, the sorted() function is used to sort odd-indexed and even-indexed elements of the array separately, and then assign them back to the original array using slicing.
This replaces the first for loop in the original code. The rest of the code remains the same.
Below is the code for the above approach:
Python3
def oddEvenSort(arr, n):
isSorted = 0
while isSorted = = 0 :
isSorted = 1
arr[ 1 :: 2 ], arr[ 2 :: 2 ] = sorted (arr[ 1 :: 2 ]), sorted (arr[ 2 :: 2 ])
for i in range ( 0 , n - 1 , 2 ):
if arr[i] > arr[i + 1 ]:
arr[i], arr[i + 1 ] = arr[i + 1 ], arr[i]
isSorted = 0
return
arr = [ 34 , 2 , 10 , - 9 ]
n = len (arr)
oddEvenSort(arr, n);
for i in range ( 0 , n):
print (arr[i], end = " " )
|
Time Complexity: O(n2)
Auxiliary Space: O(1)
Please refer complete article on Odd-Even Sort / Brick Sort for more details!
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
28 Aug, 2023
Like Article
Save Article