I wrote a method to find the second smallest number in an array without using sort.I thought I could extend the same logic to find the third smallest in the array..However I realised it was not so easy..My brain must be addled by lack of sleep or something..Below is my code for findSecondSmallest and findThirdSmallest.. Can someone correct the flaw in my logic for the later?
public class ArrayElementSelection{
public static int findSecondSmallest(int[] a){
int N = a.length;
int min = 0;
int secondSmallest = 0;
for(int i=1;i<N;i++){
if(a[i] < a[min]){
secondSmallest = min;
min = i;
}else if(a[i] < a[secondSmallest]){
secondSmallest = i;
}
}
return a[secondSmallest];
}
public static int findThirdSmallest(int[] a){
int N = a.length;
int min = 0;
int secondSmallest = 0;
int thirdSmallest = 0;
for(int i=1;i<N;i++){
if(a[i] < a[min]){
min = i;
}else if(a[i] < a[secondSmallest]){
secondSmallest = i;
}else if(a[i]< a[thirdSmallest]){
thirdSmallest = i;
}
}
return a[thirdSmallest];
}
public static void main(String[] args) {
int[] a = new int[]{4,2,3,1,5};
System.out.println(findThirdSmallest(a));
}
}
>> 4