This program finds the second largest element in a 1-D array in a single pass, without sorting the array.
C Program
#include <stdio.h>
#include <limits.h>
int main() {
int arr[100], n, i;
int largest = INT_MIN, second = INT_MIN;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter %d elements:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
for (i = 0; i < n; i++) {
if (arr[i] > largest) {
second = largest;
largest = arr[i];
} else if (arr[i] > second && arr[i] != largest) {
second = arr[i];
}
}
if (second == INT_MIN) {
printf("There is no second largest element (all elements may be equal).\n");
} else {
printf("Largest element: %d\n", largest);
printf("Second largest element: %d\n", second);
}
return 0;
}
Explanation
largestandsecondboth start atINT_MINso any real array value will be greater on the first comparison.- While scanning, whenever a new element beats
largest, the oldlargestis demoted tosecondbefore updatinglargest. - Otherwise, if the element is between
secondandlargest(and not equal tolargest, to avoid counting a duplicate maximum as the second largest), it becomes the newsecond. - This does the job in one pass (O(n)) instead of sorting the whole array first.
Sample Output
Enter number of elements: 6
Enter 6 elements:
10 25 8 25 17 3
Largest element: 25
Second largest element: 17