C Online Compiler
Example: Odd-Even Sort Implementation in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Odd-Even Sort Implementation #include <stdio.h> #include <stdbool.h> // For boolean type // Function to swap two integers void swap(int* xp, int* yp) { int temp = *xp; *xp = *yp; *yp = temp; } // Function to print an array void printArray(int arr[], int size) { for (int i = 0; i < size; i++) { printf("%d ", arr[i]); } printf("\n"); } // Function to implement Odd-Even Sort void oddEvenSort(int arr[], int n) { bool isSorted = false; // Initially assume array is not sorted // Step 1: Loop until no swaps are made in an entire pass while (!isSorted) { isSorted = true; // Assume sorted for this pass, if no swaps, it's true // Step 2: Perform Odd Phase (compare and swap odd-indexed pairs) // Compare (arr[1], arr[2]), (arr[3], arr[4]), etc. for (int i = 1; i <= n - 2; i += 2) { if (arr[i] > arr[i+1]) { swap(&arr[i], &arr[i+1]); isSorted = false; // A swap occurred, so array is not fully sorted yet } } // Step 3: Perform Even Phase (compare and swap even-indexed pairs) // Compare (arr[0], arr[1]), (arr[2], arr[3]), etc. for (int i = 0; i <= n - 2; i += 2) { if (arr[i] > arr[i+1]) { swap(&arr[i], &arr[i+1]); isSorted = false; // A swap occurred, so array is not fully sorted yet } } } } int main() { // Step 1: Define an array to be sorted int arr[] = {5, 2, 4, 1, 3, 6}; int n = sizeof(arr) / sizeof(arr[0]); printf("Original array: "); printArray(arr, n); // Step 2: Apply Odd-Even Sort oddEvenSort(arr, n); printf("Sorted array: "); printArray(arr, n); return 0; }
Output
Clear
ADVERTISEMENTS