搜索算法java
二分搜索编码示例算法
public class BinarySeacher { public static void main(String[] args) { int[] arr={1,2,3,4,5,6,7,8,9}; int index=binarySeacher(arr, 6); System.out.println("索引为:"+index); } //从数组arr中找到元素key的索引。 static int binarySeacher(int[] arr, int key) { int low=0; int high=arr.length-1; while(arr[low]<=arr[high]){ System.out.println("搜索区间为:"+low+"^^^^^^^^^^^^^^^^^"+high); int midIndex = (low+high)>>1; if(arr[midIndex] > key){ high = midIndex-1; } else if(arr[midIndex] < key){ low = midIndex+1; } else{ return midIndex; } } return -1; } }
二分搜索编码示例运行结果数组
搜索区间为:0^^^^^^^^^^^^^^^^^8 搜索区间为:5^^^^^^^^^^^^^^^^^8 搜索区间为:5^^^^^^^^^^^^^^^^^5 索引为:5