C program to implement Odd-even sort algorithm

Here, we are going to learn how to implement Odd-even sort algorithm using C program?
Submitted by Nidhi, on August 16, 2021

Problem Solution:

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.

Program:

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.

Preparation

What's New

Top Interview Coding Problems/Challenges!