Recently went to a company interview, the hands of the CTO in front of others volunteered to write a bubbling method, the results in the exchange of data at the time of a fool, home to reflect, write the following code, to oneself is a spur, get the lesson is not above his business, low-key forward.
1 PackageCom.defymedia.interview.sort;2 3 Importjava.util.ArrayList;4 Importjava.util.List;5 ImportJava.util.Random;6 7 Public classSimplesort {8 9 Public Static Final intNo_match =-1;Ten One Public<textendscomparable> list<t> Sort (list<t>list) { A intSize = list! =NULL? List.size (): 0; - if(size = = 0)return NULL; - the for(inti = 0; i < size; i++) { - for(intj = i + 1; J < size; J + +) { - if(List.get (i). CompareTo (List.get (j)) > 0) { -T temp =List.get (i); + List.set (I, List.get (j)); - List.set (J, temp); + } A } at } - - returnlist; - } - - Public<textendsComparable>t[] Sort (t[] ts) { in intSize = ts! =NULL? ts.length:0; - if(size = = 0)return NULL; to + for(inti = 0; i < size; i++) { - for(intj = i + 1; J < size; J + +) { the if(Ts[i].compareto (ts[j]) > 0) { *T temp =Ts[i]; $Ts[i] =Ts[j];Panax NotoginsengTS[J] =temp; - } the } + } A the returnts; + } - $ Public<textendsComparable>intBinarySearch (t[] ts, t t) { $ intLength = ts! =NULL?Ts.length:NO_MATCH; - if(Length <= 0 | | t = =NULL)returnNo_match; - the intMiddle; - intindex =No_match;Wuyi intLow = 0; the intHigh =length; - while(Low <High ) { WuMiddle = (low + high) >> 1; -T temp =Ts[middle]; About if(Temp.compareto (t) > 0) { $High =Middle; -}Else if(Temp.compareto (T) < 0) { -Low =Middle; -}Else { Aindex =Middle; + Break; the } - } $ theSystem.out.println ("index is" +index); the returnindex; the } the - Public Static voidmain (string[] param) { inSimplesort Simplesort =NewSimplesort (); the intSize = 10; theRandom random =NewRandom (); Aboutlist<integer> list =NewArraylist<>(size); the for(inti = 0; i < size; i++) { theList.add (Random.nextint (20)); the } +List =Simplesort.sort (list); - for(comparable comparable:list) { the System.out.println (comparable.tostring ());Bayi } theinteger[] data =NewInteger[size]; the for(inti = 0; i < size; i++) { -Data[i] = Random.nextint (50); - } thedata =simplesort.sort (data); the for(comparable comparable:data) { the System.out.println (comparable.tostring ()); the } - intNumber =No_match; the simplesort.binarysearch (data, number); the } the}
Java bubbling method and dichotomy method