I'm trying to create two method one that finds the smallest and one that finds the second smallest value in an Array of objects.
I've written the two like this
public static BanffMarathonRunner getFastestTime(BanffMarathonRunner[] runner){
if(runner.length == 0){
return null;
}
BanffMarathonRunner fastest = runner[0];
for(int i = 0; i< runner.length; i++){
BanffMarathonRunner now = runner[i];
if(now.Time < fastest.Time){
fastest = now;
}
}
return fastest;
}
public static BanffMarathonRunner getSecondFastestTime(BanffMarathonRunner[] runner){
if(runner.length == 0){
return null;
}
BanffMarathonRunner fastest = runner[0];
BanffMarathonRunner secondFastest = runner[0];
for(int i = 0; i< runner.length; i++){
BanffMarathonRunner now = runner[i];
if(now.Time < fastest.Time){
fastest = now;
for(int j = 0; j< runner.length; j++){
BanffMarathonRunner now2 = runner[j];
if(now2.Time < secondFastest.Time){
secondFastest = now2;
if(now2.Time == fastest.Time){
secondFastest = secondFastest;
}
}
}
}
}
return secondFastest;
}
I've figured out the how to find the smallest value, I just need to find the second smallest and I'm not sure how.
Any Ideas? Thanks!
-
1Why not remove the fastest from the array and then run your function to find the fastest one from the times that are left?APerson– APerson2014年10月22日 02:58:33 +00:00Commented Oct 22, 2014 at 2:58
3 Answers 3
Arrays.sort(test);
if(test.length-2 >= 0)
System.out.println(test[test.length-2]);
something like this:
findSecondSmallest anArray[]:
if anArray.length < 2:
return null;
fastest = anArray[0];
secondFastest = anArray[1];
if fastest > secondFastest:
fastest = anArray[1];
secondFastest = anArray[0]
for each element in anArray:
if element < fastest:
secondFastest = fastest;
fastest = element;
else if element < secondFastest:
secondFastest = element;
return secondFastest
-
Please mark my answer as correct with the green check, thanks!Andrew Luo– Andrew Luo2014年10月22日 03:20:23 +00:00Commented Oct 22, 2014 at 3:20
-
This is not even Java syntax.Koray Tugay– Koray Tugay2014年10月22日 14:27:44 +00:00Commented Oct 22, 2014 at 14:27
-
it's just pseudocode, the question was more of an algorithmic one.Andrew Luo– Andrew Luo2014年10月22日 14:30:51 +00:00Commented Oct 22, 2014 at 14:30
Once you know the fastest runner, store the index of this entry. Then when finding the 2nd fastest runner, ignore the index of Fastest runner in the loop using 'continue'
Also for any K-smallest entry, you can see the idea given on this question: K smallest in Array Java