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

The odd-even sort, also known as brick sort, is a comparison-based sorting algorithm that divides the sorting process into two alternating phases: odd phase and even phase. This technique is similar to bubble sort but operates on different index pairs in each phase, making it suitable for parallel processing.

The odd phase compares and swaps elements at odd indices (1, 3, 5...) with their adjacent elements, while the even phase works on even indices (0, 2, 4...) with their adjacent elements.

Syntax

void oddEvenSort(int arr[], int n);

How It Works

The algorithm alternates between two phases until the array is completely sorted −

  • Odd Phase: Compare elements at indices (1,2), (3,4), (5,6)... and swap if out of order
  • Even Phase: Compare elements at indices (0,1), (2,3), (4,5)... and swap if out of order

Example

Here's a complete implementation of the odd-even sort algorithm −

#include <stdio.h>
#include <stdbool.h>

void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

void oddEvenSort(int arr[], int n) {
    bool isSorted = false;
    
    while (!isSorted) {
        isSorted = true;
        
        /* Odd phase: compare odd indexed elements with next element */
        for (int i = 1; i < n - 1; i += 2) {
            if (arr[i] > arr[i + 1]) {
                swap(&arr[i], &arr[i + 1]);
                isSorted = false;
            }
        }
        
        /* Even phase: compare even indexed elements with next element */
        for (int i = 0; i < n - 1; i += 2) {
            if (arr[i] > arr[i + 1]) {
                swap(&arr[i], &arr[i + 1]);
                isSorted = false;
            }
        }
    }
}

void printArray(int arr[], int n) {
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

int main() {
    int arr[] = {3, 5, 7, 6, 1, 4, 2};
    int n = sizeof(arr) / sizeof(arr[0]);
    
    printf("Original array: ");
    printArray(arr, n);
    
    oddEvenSort(arr, n);
    
    printf("Sorted array: ");
    printArray(arr, n);
    
    return 0;
}
Original array: 3 5 7 6 1 4 2 
Sorted array: 1 2 3 4 5 6 7 

Key Points

  • Time Complexity: O(n²) in worst case, O(n) in best case
  • Space Complexity: O(1) as it sorts in-place
  • Stability: Stable sorting algorithm
  • Designed for parallel processing where multiple comparisons can happen simultaneously

Conclusion

Odd-even sort is an efficient parallel sorting algorithm that alternates between odd and even phases. While not commonly used in sequential programming due to its O(n²) complexity, it demonstrates excellent parallel processing capabilities.

Updated on: 2026-03-15T11:32:04+05:30

588 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements