Home »
C/C++ Data Structure Programs
C program to implement Odd-even sort algorithm
Odd-even sort algorithm: In this tutorial, we will learn about the Odd-even sort algorithm and the implementation of the Odd-even sort algorithm using the C program.
By Nidhi Last updated : August 06, 2023
Odd-even sort algorithm
An odd-even sort is also known as an odd-even transposition sort or brick sort or parity sort. It is a relatively very simple sorting algorithm, which is developed originally for use on parallel processors with local interconnections. It is a comparison sort related to bubble sort, with which it shares many characteristics. It functions by comparing all odd/even indexed pairs of adjacent elements in the list and, if a pair is in the wrong order (the first is larger than the second) the elements are switched. The next step repeats this for even/odd indexed pairs (of adjacent elements). Then it alternates between odd/even and even/odd steps until the list is sorted. Read more at Odd-even sort Wikipedia
Problem statement
Here, we will create an array of integers then we will read array elements from the user and implement the Odd-even sort algorithm to arrange array elements in ascending order.
C program to implement Odd-even sort algorithm
The source code to implement the Odd-even sort algorithm is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.
// C program to implement Odd-even sort algorithm
#include <stdio.h>
#define MAX 7
void Exchange(int* num1, int* num2)
{
int temp;
temp = *num1;
*num1 = *num2;
*num2 = temp;
}
void OddEvensort(int* arr)
{
int flag = 0;
int i = 0;
while (!flag) {
flag = 1;
i = 1;
while (i < MAX) {
if (arr[i] > arr[i + 1]) {
Exchange(&arr[i], &arr[i + 1]);
flag = 0;
}
i = i + 2;
}
i = 0;
while (i < MAX - 1) {
if (arr[i] > arr[i + 1]) {
Exchange(&arr[i], &arr[i + 1]);
flag = 0;
}
i = i + 2;
}
}
}
int main()
{
int arr[MAX];
int i = 0;
printf("Enter array elements:\n");
while (i < MAX) {
printf("Element[%d]: ", i);
scanf("%d", &arr[i]);
i++;
}
OddEvensort(arr);
printf("Sorted Array: \n");
i = 0;
while (i < MAX) {
printf("%d ", arr[i]);
i++;
}
printf("\n");
return 0;
}
Output
Enter array elements:
Element[0]: 14
Element[1]: 45
Element[2]: 23
Element[3]: 87
Element[4]: 56
Element[5]: 45
Element[6]: 98
Sorted Array:
14 23 45 45 56 87 98
Explanation
Here, we created three functions Exchange(), OddEvenSort(), and main(). The Exchange() function is used to swap values of specified variables. The OddEvensort() function is used to arrange array elements in ascending order.
In the main() function, we created an array of integers arr. Then we sorted the elements of the array using OddEvensort() function and printed the sorted array on the console screen.