Find the second largest distinct value in one pass. Report when there is none (all values equal).
#include <stdio.h>
#include <limits.h>
int second_largest(const int *a, int n, int *out) {
int first = INT_MIN, second = INT_MIN;
for (int i = 0; i < n; i++) {
if (a[i] > first) {
second = first;
first = a[i];
} else if (a[i] < first && a[i] > second) {
second = a[i];
}
}
if (second == INT_MIN)
return 0; /* fewer than two distinct values */
*out = second;
return 1;
}
int main(void) {
int a[] = {12, 35, 1, 10, 35, 34};
int b[] = {7, 7, 7};
int s;
if (second_largest(a, 6, &s))
printf("second largest = %d\n", s);
if (!second_largest(b, 3, &s))
printf("no second largest in b\n");
return 0;
}
second largest = 34 no second largest in b
Keep the two best values seen so far. The duplicate 35 is skipped by a[i] < first, so the answer is 34, not 35. One pass, O(n) time, O(1) memory – better than sorting.