• 07-27-2010, 07:45 PM
siri.th
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 PM
PhHein
Code:

```yourArray Arrays.sort(yourArray) sysout(yourArray[yourArray.length-2])```
All without a loop.
• 07-27-2010, 09:42 PM
Norm
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 AM
xorhazard81x
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);```
Hopefully, I got the right algorithm.
• 07-28-2010, 05:13 AM
Eranga
Quote:

Originally Posted by PhHein
Code:

```yourArray Arrays.sort(yourArray) sysout(yourArray[yourArray.length-2])```
All without a loop.

This is the most easiest way to move, no point of stuck with complex logics.
• 07-28-2010, 08:37 AM
xorhazard81x
Quote:

Originally Posted by Eranga
This is the most easiest way to move, no point of stuck with complex logics.

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).