C/C++ Program for Odd-Even Sort (Brick Sort)?


Here we will see how the brick sort works. The Brick sort is one modification of bubble sort. This algorithm is divided into two parts. These parts are odd part and even parts. In the odd part we will use the bubble sort on odd indexed items, and in the even part we will use the bubble sort on even indexed elements. Let us see the algorithm to get the idea.

Algorithm

brickSort(arr, n)

begin
   flag := false
   while the flag is not true, do
      flag := true
      for i := 1 to n-2, increase i by 2, do
         if arr[i] > arr[i+1], then
            exchange arr[i] and arr[i+1]
            flag := false
         end if
      done
      for i := 0 to n-2, increase i by 2, do
         if arr[i] > arr[i+1], then
            exchange arr[i] and arr[i+1]
            flag := false
         end if
      done
   done
end

Example

 Live Demo

#include<iostream>
using namespace std;
void brickSort(int arr[], int n){
   bool flag = false;
   while(!flag){
      flag = true;
      for(int i = 1; i<n-1; i= i+2){
         if(arr[i] > arr[i+1]){
            swap(arr[i], arr[i+1]);
            flag = false;
         }
      }
      for(int i = 0; i<n-1; i= i+2){
         if(arr[i] > arr[i+1]){
            swap(arr[i], arr[i+1]);
            flag = false;
         }
      }
   }
}
main() {
   int data[] = {54, 74, 98, 154, 98, 32, 20, 13, 35, 40};
   int n = sizeof(data)/sizeof(data[0]);
   cout << "Sorted Sequence ";
   brickSort(data, n);
   for(int i = 0; i <n;i++){
      cout << data[i] << " ";
   }
}

Output

Sorted Sequence 13 20 32 35 40 54 74 98 98 154

Updated on: 01-Jul-2020

336 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements