I am wondering if this is the most efficient way to find the nth highest number in an unsorted array. What I did was sort it with mergeSort then find the index of the nth highest number. I think this is more efficient than most searches but I am not quite sure.....
import java.util.Arrays;
public class ThirdHighest {
public static void main(String[] args) {
// TODO Auto-generated method stub
int [] a = new int[]{3,5,6,7,8,2,1,10,9};
System.out.print(Arrays.toString(a));
mergeSort(a);
System.out.print(Arrays.toString(a));
System.out.print(nHighestValue(a, 3));
}
public static void mergeSort(int[] arr) {
if(arr.length > 1) {
int lengthLeft = arr.length / 2;
int [] left = Arrays.copyOfRange(arr, 0, lengthLeft);
int [] right = Arrays.copyOfRange(arr, lengthLeft, arr.length);
mergeSort(left);
mergeSort(right);
merge(arr, left, right);
}
}
public static void merge(int[] result, int[] left, int[] right){
int l1 = 0;
int r2 = 0;
while(l1 < left.length || r2 < right.length) {
if(l1 == left.length) {
result[l1+r2] = right[r2];
r2 += 1;
} else if(r2 == right.length){
result[l1+r2] = left[l1];
l1 += 1;
} else if(left[l1] < right[r2]) {
result[l1 + r2] = left[l1];
l1 += 1;
} else {
result[l1+r2] = right[r2];
r2 += 1;
}
}
}
public static int nHighestValue(int[] a, int n) {
int index = a.length - n;
return a[index];
}
}