C Online Compiler
Example: Even-Odd Sort using Auxiliary Array in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Even-Odd Sort using Auxiliary Array #include <stdio.h> #include <stdlib.h> // For malloc and free void evenOddSortAuxiliary(int arr[], int n) { // Step 1: Allocate memory for a temporary array int *temp_arr = (int *)malloc(n * sizeof(int)); if (temp_arr == NULL) { printf("Memory allocation failed!\n"); return; } int k = 0; // Index for the temporary array // Step 2: Copy all even numbers to the temporary array for (int i = 0; i < n; i++) { if (arr[i] % 2 == 0) { temp_arr[k++] = arr[i]; } } // Step 3: Copy all odd numbers to the temporary array for (int i = 0; i < n; i++) { if (arr[i] % 2 != 0) { temp_arr[k++] = arr[i]; } } // Step 4: Copy elements back from temporary array to original array for (int i = 0; i < n; i++) { arr[i] = temp_arr[i]; } // Step 5: Free the allocated memory free(temp_arr); } 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); evenOddSortAuxiliary(arr, n); printf("Sorted array (Auxiliary Array): "); printArray(arr, n); int arr2[] = {7, 2, 10, 5, 1, 8, 4}; n = sizeof(arr2) / sizeof(arr2[0]); printf("Original array: "); printArray(arr2, n); evenOddSortAuxiliary(arr2, n); printf("Sorted array (Auxiliary Array): "); printArray(arr2, n); return 0; }
Output
Clear
ADVERTISEMENTS