對已經(jīng)排好序的數(shù)組適用
01 |
public class SplitBy2{ |
02 |
???? static int num= 12 ; |
03 |
???? static int [] arr={ 1 , 3 , 7 , 11 , 12 , 17 , 23 , 25 , 27 }; |
04 |
???? static int start,end,index; |
05 |
??? public static void main(String[] args){ |
06 |
????? System.out.println(splitBy2(arr,num)); |
07 |
? } |
08 |
??? public static int splitBy2( int arr[], int num){ |
09 |
??????? start= 0 ; |
10 |
??????? end=arr.length- 1 ; |
11 |
????? while ( true ){ |
12 |
????? index=(start+end)/ 2 ; |
13 |
????? if (arr[index]==num){ |
14 |
?????? return index; |
15 |
????? } else if (start>end){ |
16 |
?????? System.out.println( "沒有找到" ); |
17 |
?????? return - 1 ; |
18 |
???? } else { |
19 |
?????? if (arr[index]>num){ |
20 |
??????? end=index- 1 ; |
21 |
??????? } |
22 |
?????? if (arr[index]<num){ |
23 |
??????? start=index+ 1 ; |
24 |
??????? } |
25 |
????? } |
26 |
??? } |
27 |
?? } |
28 |
} |