C Online Compiler
Example: Even-Odd Sort using qsort in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Even-Odd Sort using qsort #include <stdio.h> #include <stdlib.h> // For qsort // Comparison function for qsort int compareEvenOdd(const void *a, const void *b) { int num1 = *(const int *)a; int num2 = *(const int *)b; // Prioritize even numbers over odd numbers if (num1 % 2 == 0 && num2 % 2 != 0) { return -1; // num1 (even) comes before num2 (odd) } if (num1 % 2 != 0 && num2 % 2 == 0) { return 1; // num1 (odd) comes after num2 (even) } // If both are even or both are odd, their relative order is not strictly defined // by this comparison for stability. qsort might not preserve it. // For simple even/odd separation, 0 (equal) is sufficient here. return 0; } void evenOddSortQsort(int arr[], int n) { // Step 1: Call qsort with the custom comparison function qsort(arr, n, sizeof(int), compareEvenOdd); } void printArray(int arr[], int n) { for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); } int main() { int arr[] = {12, 34, 45, 9, 8, 90, 3}; int n = sizeof(arr) / sizeof(arr[0]); printf("Original array: "); printArray(arr, n); evenOddSortQsort(arr, n); printf("Sorted array (qsort): "); printArray(arr, n); int arr2[] = {7, 2, 10, 5, 1, 8, 4}; n = sizeof(arr2) / sizeof(arr2[0]); printf("Original array: "); printArray(arr2, n); evenOddSortQsort(arr2, n); printf("Sorted array (qsort): "); printArray(arr2, n); return 0; }
Output
Clear
ADVERTISEMENTS