Bookmark and Share

free counters
Back to Problem list

Problem 3: Given a set of integer numbers. Write a program to find the Second highest number.

You can solve this problem easily by sorting those integers and then print the 2nd elements. But hence we will try to solve this problem by linear time.

First take two variables, max_1, max_2. max_1 will hold the maximum number and max_2 will hold the 2nd highest number.
Set max_1 = Array[0], i.e first element of the given set of integers and max_2 = 0;

Now take each element, compare with first max_1, if the number is greater than max_1, then max_2 = max_1 and max_1 = new elements.
If the number greater than max_2 but less than max_1, then set max_2 = new elements.

Analysis:

Let Given integer set is: 5 4 7 8 9 1 2 3 4 5 9 10 25 11
set max_1 = 5 ( First element of the set)
set max_2 = 0

now take each element and compare with max_1 and max_2,

First 4 ( 5 already taken )
max_1 > 4 ? false, so, no change to max_1, but max_2 < 4 , so update max_2 , set max_2 = 4

Then 7,
max_1 > 7, so, max_2 = max_1, that is max_2 will be 5, and then set max_1 = 7

Next 8
max_1 > 8, so max_2 = max_1, that is max_2 = 7 and then set max_1 = 8

repeat this procedure until the last number appear.

Source Code:

#include<stdio.h>

int A[100];

int secondMax(int n) {
	int i, max_1 = A[0], max_2 = 0;
	for(i = 1; i<n; i++) {
		if(A[i] > max_1) {
			max_2 = max_1;
			max_1 = A[i];
		}else if(A[i] > max_2) {
			max_2 = A[i];
		}
	}
	return max_2;
}

int main() {
	int i, n, max_2;
	scanf("%d",&n);
	for(i = 0; i<n; i++) scanf("%d",&A[i]);
	max_2 = secondMax(n);
	printf("%d\n",max_2);
	return 0;
}

Back to Problem list