I was implementing a code to return the nth Largest Number in an array, Following is the code I implemented;
public int getNthLargestNum(int [] givenArr, int n){
int nTotal=0;
int nNthNum = -1;
// Remove Duplicates
Set<Integer> o_hs = new TreeSet<Integer>();
for(int insert=0; insert<givenArr.length; insert++)
{o_hs.add(givenArr[insert]);}
Iterator it = o_hs.iterator();
int count=0;
while(it.hasNext()){
if(count == n){
// IF I MOVE THE LINE HERE
// nNthNum = (Integer)it.next();
break;
}
nNthNum = (Integer)it.next();
count++;
}
return nNthNum;
}
If I input the array givenArr[4,14,4,5,6,8,9] and n=2 the output is 5 for the above program but if I move the line nNthNum = (Integer)it.next(); inside the if loop it outputs 4.
So I was curious to know to iterate through the loop we should always implement it.next()?