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.
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.
All without a loop.Code:yourArray
Arrays.sort(yourArray)
sysout(yourArray[yourArray.length-2])
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.
This one may work :
Hopefully, I got the right algorithm.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);
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".