C Online Compiler
Example: Find Second Smallest by Sorting in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Find Second Smallest by Sorting #include <stdio.h> #include <stdlib.h> // Required for qsort // Comparison function for qsort int compare(const void *a, const void *b) { return (*(int*)a - *(int*)b); } int main() { int arr[] = {5, 2, 8, 1, 9, 2}; // Example array with duplicates int n = sizeof(arr) / sizeof(arr[0]); // Step 1: Handle edge cases for array size if (n < 2) { printf("Array size must be at least 2 to find the second smallest element.\n"); return 1; } // Step 2: Sort the array using qsort qsort(arr, n, sizeof(int), compare); // Step 3: Find the second smallest unique element int firstSmallest = arr[0]; int secondSmallest = -1; // Initialize with a value indicating not found for (int i = 1; i < n; i++) { if (arr[i] > firstSmallest) { secondSmallest = arr[i]; break; // Found the first element greater than the smallest } } if (secondSmallest != -1) { printf("The array is: "); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\nThe second smallest element is: %d\n", secondSmallest); } else { printf("No second smallest element found (all elements might be the same).\n"); } return 0; }
Output
Clear
ADVERTISEMENTS