• C

# Highest second value

How to find the second highest integer from an integer array without soring the array? A sample program would help a lot.
###### Who is Participating?

Commented:
I think the function posted above always returns the highest and not the second highest because in the loop it always sets high2 to the highest encountered and then copies it up to high1.

This way resets high1 only if the indexed value is greater than high1, and if not then it checks if it should set high2...?

--
#include <stdio.h>

#define MIN(x, y) (x > y ? y : x)
#define MAX(x, y) (x > y ? x : y)

int find2high(int data[], int ndata)
{
int i, high1, high2;

if (ndata <= 1)
{
return 0;
}

high1 = MAX(data[0], data[1]);
high2 = MIN(data[0], data[1]);

for (i=2; i < ndata;i++)
{
if (data[i] > high1)
{
high2 = high1;
high1 = data[i];
}
else if (data[i] > high2)
{
high2 = data[i];
}
}

return high2;
}

int main(int argc, char **argv)
{
int x[] = { 30, 20, 70, 60, 10, 80, 45, 11, 100 };

printf("second highest: %d\n", find2high(x, sizeof(x) / sizeof (int)));

return 0;
}
0

Commented:

int find2high(int data[], ini ndata)
{
int i, high1, high2;
if (ndata <= 1) return 0;
high1 = max(data[0], data[1]);
high2 = max(data[0], data[1]);
for (i=2; i<ndata;i++) {
if (data[i] > high2) {
high2 = data[i];
if (high2 > high1) high1 = high2;
}
}
return high2;
}

Is it a homework ?
0

Commented:
correction
high1 = max(data[0], data[1]);
high2 = min(data[0], data[1]);
^^^
0

Commented:
...or, if you wanted only one test to occur for most of the integers tested, you could do it like:

int find2high(int data[], int ndata)
{
int i, high1, high2;

if (ndata <= 1)
{
return 0;
}

high1 = MAX(data[0], data[1]);
high2 = MIN(data[0], data[1]);

for (i=2; i<ndata;i++)
{
if (data[i] > high2)
{
if (data[i] > high1)
{
high2 = high1;
high1 = data[i];
}
else
{
high2 = data[i];
}
}
}

return high2;
}

So if the value is less than the current 'high2', it is only tested once.  If its greater than high2, a subsequent test checks to see if its greater than high1.
0

Commented:
int max1, max2;
int arr[10] = {1,10,30,2,7,8,9,23,79,22};
int ele = 0;

max1 = max2 = arr[0];

for (ele = 1; ele < 10; ele ++)
{
if (max1 < arr[ele])
{
max2 = max1;
max1 = arr[ele];
}
}

printf("%d",max2);
0

Commented:
umangjoshi:

I don't think your algorithm works for:

int arr[10] =   {1,10,30,2,7,8,9,23,79,45};

(change the last element from 22 to 45).  max2 would still be set to 30.  I think...  Just walking through my head.

And for a 1 element array it would say the second highest is the only element, which is not true.
0

Author Commented:
thanx for helping out... i too worked out the same problem but in a slightly simplified way..... thanx so much
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.