Brick Sort Algorithm in Python [Easily Implemented]

Feature Img Brick Sort

In this tutorial, we will be learning how to implement the Brick Sort algorithm in order to sort the elements in an array. It’s unknown in the coding world but there is no harm in learning a new sorting technique.

Let’s first understand what brick sort is before implementing the same in the python programming language.

Also read: Insertion Sort in Python


Introduction to the Brick Sort algorithm

Brick Sort, also known as OddEven Sort which is a modified version of Bubblesort. The sorting algorithm is divided into two stages namely, odd and even stages. The control runs until the array is sorted by making sure that the even and odd stages are executed in every iteration.

Now you might ask what these odd and even stages mean? When the control is executing the odd phase, we will only be sorting the elements present at the odd indexes. In a similar pattern during the execution of the event phase, the control will only be sorting the elements at the even indexes.


Brick Sort Algorithm Implementation

In order to implement the brick sort, we will be following a number of steps and the same is mentioned below.

  • Declare the brick sort function to perform the sort and also take a variable to switch between the odd and even phases.
  • Create a variable isSort with initial value as 0. The purpose of this variable is to keep of track the current phase.
  • Run a while loop to iterate until isSort is equal to 1.
    1. Create a inner for loop to sort the odd entries.
    2. Similarly create another inner for loop to sort even entries.
  • Once the sorting is done, we return the result.

Implementing Brick Sort in Python

Let’s get right into the implementation of the brick sort algorithm in Python and make sure that we can get the expected output.

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 = [31, 76, 18, 2, 90, -6, 0, 45, -3] 
n = len(array)
print("Array input by user is: ", end="")
for i in range(0, n): 
    print(array[i], end =" ")   
brickSort(array, n);
print("\nArray after brick sorting is: ", end="")
for i in range(0, n): 
    print(array[i], end =" ") 

The code mentioned above is shown below. You can see that the array is sorted successfully.

Array input by user is: 31 76 18 2 90 -6 0 45 -3 
Array after brick sorting is: -6 -3 0 2 18 31 45 76 90 

Conclusion

I hope today you learned about a new sorting algorithm. Though it is not really asked much but, it’s always better to have some extra knowledge in your pockets!

Thank you for reading! Happy learning! 😇