hi to all

a tried a lot and asked many for getting second highest in the array using only one loop. but am not succeeded. please anyone help me.

- 07-27-2010, 07:45 PMsiri.thplease help me in finding second highest in an array using single loop
hi to all

a tried a lot and asked many for getting second highest in the array using only one loop. but am not succeeded. please anyone help me. - 07-27-2010, 07:49 PMPhHeinCode:
`yourArray`

Arrays.sort(yourArray)

sysout(yourArray[yourArray.length-2])

- 07-27-2010, 09:42 PMNorm
Can you show us your code and describe where your problem is?

Have you worked out a design for finding the answer? You need that before you write code. - 07-28-2010, 04:55 AMxorhazard81x
This one may work :

Code:`int [] ar={1,5,6,2,9,5,7,7,8,3};`

int first=ar[0];

int second=0;

int tmpFirst=0;

for(int i=1;i<ar.length;i++)

{

if(first<ar[i])

{

tmpFirst=first;

first=ar[i];

second=tmpFirst;

}

if(second<ar[i] && first!=ar[i])

second=ar[i];

}

System.out.println("first : "+first+" ; second : "+second);

- 07-28-2010, 05:13 AMEranga
- 07-28-2010, 08:37 AMxorhazard81x
Actually, sort() compares between each value in an array more than one time.

Hence, it fails to do as we have been asked in the question.

BTW - sort() uses tuned-quick-sort algorithm, which means O(n*log n), while we need O(n).

For more information, google "quick-sort" & "tuned quick-sort" & "sort() in java". - 07-28-2010, 09:21 AMEranga