Thursday, September 4, 2025
HomeData Modelling & AIJava Program for Odd-Even Sort / Brick Sort

Java 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. 

Java




// Java Program to implement
// Odd-Even / Brick Sort
import java.io.*;
 
class GFG {
    public static void oddEvenSort(int arr[], int n)
    {
        boolean isSorted = false; // Initially array is unsorted
 
        while (!isSorted) {
            isSorted = true;
            int temp = 0;
 
            // Perform Bubble sort on odd indexed element
            for (int i = 1; i <= n - 2; i = i + 2) {
                if (arr[i] > arr[i + 1]) {
                    temp = arr[i];
                    arr[i] = arr[i + 1];
                    arr[i + 1] = temp;
                    isSorted = false;
                }
            }
 
            // Perform Bubble sort on even indexed element
            for (int i = 0; i <= n - 2; i = i + 2) {
                if (arr[i] > arr[i + 1]) {
                    temp = arr[i];
                    arr[i] = arr[i + 1];
                    arr[i + 1] = temp;
                    isSorted = false;
                }
            }
        }
 
        return;
    }
    public static void main(String[] args)
    {
        int arr[] = { 34, 2, 10, -9 };
        int n = arr.length;
 
        oddEvenSort(arr, n);
        for (int i = 0; i < n; i++)
            System.out.print(arr[i] + " ");
 
        System.out.println(" ");
    }
}
// Code Contribute by Mohit Gupta_OMG <(0_o)>


Output:

-9 2 10 34

Time Complexity : O(N2) where, N = Number of elements in the input 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!

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Dominic
32260 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6625 POSTS0 COMMENTS
Nicole Veronica
11795 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11855 POSTS0 COMMENTS
Shaida Kate Naidoo
6747 POSTS0 COMMENTS
Ted Musemwa
7023 POSTS0 COMMENTS
Thapelo Manthata
6694 POSTS0 COMMENTS
Umr Jansen
6714 POSTS0 COMMENTS