java - third smallest element in array -


this question has answer here:

i wrote method find second smallest number in array without using sort.i thought extend same logic find third smallest in array..however realised not easy..my brain must addled lack of sleep or something..below code findsecondsmallest , findthirdsmallest.. can correct flaw in logic 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[] = new int[]{4,2,3,1,5};          system.out.println(findthirdsmallest(a));     } }  >> 4 

okay let's clean bit. want find third smallest element in array.

    navigableset<integer> min3 = new treeset<integer>();     //we keep 3 elements in min3, set size grows on 3     //we remove last element, max.      (int x : array) {         min3.add(x);         if (min3.size() > 3) {             min3.polllast();         }      }      if (array.length >= 3) {         integer thirdminimum = min3.polllast();         system.out.println(thirdmimimum);     } else {        //array must contain @ least 3 elements     } 

the above code snippet finds third unique minimum. instead of set of integers, if keep sorted list of integers. can find third non unique minimum.


Comments