C/C++ Program for Odd-Even Sort / Brick Sort
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.
CPP
#include <bits/stdc++.h>
using namespace std;
void oddEvenSort( int arr[], int n)
{
bool isSorted = false ;
while (!isSorted) {
isSorted = true ;
for ( int i = 1; i <= n - 2; i = i + 2) {
if (arr[i] > arr[i + 1]) {
swap(arr[i], arr[i + 1]);
isSorted = false ;
}
}
for ( int i = 0; i <= n - 2; i = i + 2) {
if (arr[i] > arr[i + 1]) {
swap(arr[i], arr[i + 1]);
isSorted = false ;
}
}
}
return ;
}
void printArray( int arr[], int n)
{
for ( int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << "\n";
}
int main()
{
int arr[] = { 34, 2, 10, -9 };
int n = sizeof (arr) / sizeof (arr[0]);
oddEvenSort(arr, n);
printArray(arr, n);
return (0);
}
|
Time Complexity : O(N2) where, N represents the number of elements in the given array.
Auxiliary Space : O(1), this is an in-place algorithm, so no extra space is required.
Please refer complete article on Odd-Even Sort / Brick Sort for more details!
Last Updated :
31 May, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...