This can be done in recursive way using BinarySearch.
Below is a BinarySearch to find the smallest. It can be extended to find smallest and second smallest (Tournament like method).
public int findSmallest(int[] A, int start, int end){
if(end == start){
return A[start];
}else if(start == end-1){
return Math.min(A[start], A[end]);
}else{
int mid = start + (end-start)/2;
int min1 = findSmallest(A, start, mid);
int min2 = findSmallest(A, mid+1, end);
return Math.min(min1, min2);
}
}
Here is the method to find Second smallest. Basic idea is to return the max when search size is <=2
. For rest of the search return min.
public static int findSecondSmallest(int[] A, int start, int end){
if(end == start){
return A[start];
}else if(start == end-1){
return Math.max(A[start], A[end]);
}else{
int mid = start + (end-start)/2;
int min1 = findSecondSmallest(A, start, mid);
int min2 = findSecondSmallest(A, mid+1, end);
return Math.min(min1, min2);
}
}