C Online Compiler
Example: Find Second Smallest in Single Pass in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Find Second Smallest in Single Pass #include <stdio.h> #include <limits.h> // Required for INT_MAX int main() { int arr[] = {5, 2, 8, 1, 9, 2}; // Example array 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: Initialize first_smallest and second_smallest // Initialize with INT_MAX to ensure any array element will be smaller int first_smallest = INT_MAX; int second_smallest = INT_MAX; // Step 3: Iterate through the array for (int i = 0; i < n; i++) { // If current element is smaller than first_smallest if (arr[i] < first_smallest) { second_smallest = first_smallest; // The old first_smallest becomes the new second_smallest first_smallest = arr[i]; // Current element is the new first_smallest } // If current element is between first_smallest and second_smallest else if (arr[i] < second_smallest && arr[i] != first_smallest) { second_smallest = arr[i]; // Current element is the new second_smallest } } // Step 4: Check if a valid second smallest element was found if (second_smallest == INT_MAX) { printf("No second smallest element found (all elements might be the same).\n"); } else { printf("The second smallest element is: %d\n", second_smallest); } return 0; }
Output
Clear
ADVERTISEMENTS