Brick Sort in Python

In this article, we will learn about Brick Sort and its implementation in Python.

What is Brick Sort?

Brick Sort is also called OddEven Sort. It is essentially a modified version of Bubblesort. The algorithm is divided into two stages, odd and even. The algorithm runs until the array is sorted, and two even and odd stages are executed in each iteration.

In the odd phase, we only sort the odd index entries, and in the event phase, we only sort the even index entries.

Brick Sort Implementation

1. We declare the bricksort function to perform the sort and also take a variable to switch between the phases.

2. We create a variable isSort and initialize its value to zero which helps to keep of track the phase.

3. Create a while loop and iterate it until isSort is equal to 1.

3.1 Create a for loop to sort the odd entries.

3.2 Similarly create a for loop to sort even entries.

4. Once the sorting is done, we return the result.

def brickSort(array, n): 
    isSort = 0
    while isSort == 0: 
        isSort = 1
        for i in range(1, n-1, 2): 
            if array[i] > array[i+1]: 
                array[i], array[i+1] = array[i+1], array[i] 
                isSort = 0
                  
        for i in range(0, n-1, 2): 
            if array[i] > array[i+1]: 
                array[i], array[i+1] = array[i+1], array[i] 
                isSort = 0
      
    return
  
  
array = [3, 67, 8, 12, 190, -67] 
n = len(array)
print("Original array")
for i in range(0, n): 
    print(array[i], end =" ")   
brickSort(array, n);
print("\nSorted array")
for i in range(0, n): 
    print(array[i], end =" ") 
      

Output

Original array
3 67 8 12 190 -67 
Sorted array
-67 3 8 12 67 190

Also, read

Leave a Reply

Your email address will not be published. Required fields are marked *