C Online Compiler
Example: Find Middle Max and Min using qsort in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Find Middle Max and Min using qsort #include <stdio.h> #include <stdlib.h> // Required for qsort // Comparison function for qsort (for ascending order) int compareIntegers(const void *a, const void *b) { return (*(int*)a - *(int*)b); } int main() { // Step 1: Get array size from user int n; printf("Enter the number of elements (min 3): "); scanf("%d", &n); if (n < 3) { printf("Please enter at least 3 elements to find middle max/min.\n"); return 1; // Indicate an error } int arr[n]; // Declare array of size n (VLA - C99 feature) // Step 2: Get array elements from user printf("Enter %d integers:\n", n); for (int i = 0; i < n; i++) { printf("Element %d: ", i + 1); scanf("%d", &arr[i]); } // Step 3: Sort the array using qsort // qsort(base, num, size, compar) // base: pointer to the first element of the array // num: number of elements in the array // size: size of each element in bytes // compar: pointer to a comparison function qsort(arr, n, sizeof(int), compareIntegers); // Step 4: Extract middle minimum and middle maximum int middleMin = arr[1]; // Second element (0-indexed) int middleMax = arr[n - 2]; // Second to last element // Step 5: Print the results printf("\nSorted Array: "); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); printf("Middle Minimum (Second Smallest): %d\n", middleMin); printf("Middle Maximum (Second Largest): %d\n", middleMax); return 0; }
Output
Clear
ADVERTISEMENTS