# Thread: please help me in finding second highest in an array using single loop

1. Member
Join Date
Jul 2010
Posts
2
Rep Power
0

## please 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.

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

3. 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.
Last edited by Norm; 07-27-2010 at 10:26 PM.

4. This one may work :

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

5. Originally Posted by PhHein
Java 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.

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

For more information, google "quick-sort" & "tuned quick-sort" & "sort() in java".

7. Originally Posted by xorhazard81x
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.
True. I'm not blaming on question, but seems it's pointless.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•