- public class ArrayDemo
- {
- public static void main (String args [])
- {
- int [] arr = {1,4,6,7,9,12,30,55,70};//数字是有序排列
- int index = halfSearch(arr,30);
- System.out.println(index);
- }
- //折半查找
- public static int halfSearch(int [] arr, int x)
- {
- int min = 0;
- int max = arr.length-1;
- int mid = (min+max)/2;
- while (arr[mid]!=x)
- {
- mid = (max+min)/2; //计算出mid的值,不然这个代码就没有意义。
- if (x<arr[mid])
- max = mid-1;
- else if (x>arr[mid])
- min = mid+1;
- if (max<min)
- return -1;
- }
- return mid;
- }
复制代码 |
|