patterncModerate
Find out the second highest in array
Viewed 0 times
findthearraysecondhighestout
Problem
I want to find the first and second highest number in an array. I could come up with one solution, but I want to know the optimum solution to do the same. Can someone help me with some alternative solution to this?
Output:
int main()
{
int arr[10] = {0,1,2,13,4,5,9,8,11,6};
int first = arr[0];
int second = arr[0];
int i;
for(i=0;i<10;i++)
{
if(first < arr[i])
{
second = first;
first = arr[i];
}
else if(second < arr[i])
{
second = arr[i];
}
}
printf("First = %d\n", first);
printf("Second = %d\n", second);
return 0;
}Output:
First = 13
Second = 11
Solution
There is a problem in your code. Assuming that input is
To fix this, you can do something like this.
Also, your program doesn't work well when
[3, 2, 1], the program will work like this.- Set
firstandsecondas 3.
- Iterate through elements noticing that nothing is larger than 3.
- Claim that 3 is the second number.
To fix this, you can do something like this.
if (arr[0] < arr[1]) {
second = arr[0];
first = arr[1];
}
else {
second = arr[1];
first = arr[0];
}
for (i = 2; i < elems; i++) {
/* Your code */
}Also, your program doesn't work well when
NaN is involved in first position. This probably doesn't really matter (currently this handles integers, not double floating point numbers), but this may be still relevant for you, as it would require some special code to handle NaN.Code Snippets
if (arr[0] < arr[1]) {
second = arr[0];
first = arr[1];
}
else {
second = arr[1];
first = arr[0];
}
for (i = 2; i < elems; i++) {
/* Your code */
}Context
StackExchange Code Review Q#57779, answer score: 12
Revisions (0)
No revisions yet.