- package com.vince.il8n;
- import java.util.Arrays;
- public class bs_009 {
- public static void main(String[] args){
- int[] number={1,2,3,14,15,16,7,8,9};
- //二分法 必须保证数列是有序的
- Arrays.sort(number);
- int index=binarySearch(number,4); //不显示
- System.out.println(index);
- }
- // 二分法
- public static int binarySearch(int[] x,int n){ //静态
- int start=0;
- int end=x.length-1;
- int mid;
- while(start<=end){
- mid=(start+end)/2;
- if(x[mid]==n){
- return mid;
- }else if(x[mid]<n){
- start=mid+1;
- }else if(x[mid]>n){
- end=mid-1;
- }
- }
- return -1;
- }
- }
复制代码 |
|