Static voidMain (string[] args) { Char[] arr =New[] {'a','b','C','D','e'}; Charv ='D'; varindex = Bisearch (arr,0,4, V); Console.WriteLine (index); Char[] arr2 =New[] {'b','C','D','e','F' }; CharV2 ='a'; varIndex2 = Bisearch (ARR2,0,4, v2); Console.WriteLine (INDEX2); Console.read (); } Static intBisearch (Char[] arr,intBintECharv) {intMinindex = B, Maxindex =e, Midindex; //There are two scenarios for the end of the loop://If Minindex is an even number Minindex = = Maxindex//otherwise it's Minindex = = MaxIndex-1 while(Minindex < Maxindex-1) {Midindex= Minindex + (maxindex-minindex)/2; if(Arr[midindex]. CompareTo (v) <=0) {Minindex=Midindex; } Else { //do not need midIndex-1, prevent minindex = = MaxindexMaxindex =Midindex; } } if(Arr[maxindex]. CompareTo (v) = =0) { returnMaxindex; } Else if(Arr[minindex]. CompareTo (v) = =0) { returnMinindex; } Else { return-1; } }
The Book of Programming beauty Picks