Brick Sort Implementation in C++

Hello everyone, in this post we are going to see the implementation of Brick Sort in C++. Brick Sort is also sometimes called as Odd/Even sort. This sort is not something new, but is a modified version of our bubble sort algorithm.

As the name suggests, it sorts the elements in a different fashion. It runs two types of phases- Even and Odd. In one iteration of the odd phase, it will sort the elements present in the odd index of the array. In the next run, it will do the same for even indexes. Hence, it’s called an  Odd-Even sort.

So let’s see how we can implement the same.

Brick Sort in C++

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

#include <bits/stdc++.h> 
using namespace std; 
void sort(int a[], int n) 
     bool s = false; 
  while (!s) { 
    s = true; 
    for (int i = 1; i <= n - 2; i = i + 2) { 
      if (a[i] > a[i + 1]) { 
        swap(a[i], a[i + 1]); 
        s = false; 
    for (int i = 0; i <= n - 2; i = i + 2) { 
      if (a[i] > a[i + 1]) { 
        swap(a[i], a[i + 1]); 
        s = false; 
     for (int i = 0; i < n; i++) 
		cout << a[i] << " "; 
	cout << "\n";  

We keep a variable ‘s’ to keep track of the phases. Next, we perform the sort as needed and then reverse the value to ‘s’. We sort the array by using the swap() function which is inbuilt in C++ STL.

Once the sorting is done, we print the new sorted values. Next, we define the main() where we input our array and get the output.

int main() 
  int a[] = { 7,8,1,4,12,-3,9,-45 }; 
  int n = sizeof(a) / sizeof(a[0]); 

  sort(a, n); 

  return (0); 
-45 -3 1 4 7 8 9 12
..Program finished with exit code 0                                                                               
Press ENTER to exit console. 

This was about Brick Sort or the Odd-Even sort in C++. I hope this was of your help.

Also read: Strand Sort in C++

Leave a Reply