二分搜索法

来源:互联网 发布:爱知时计电机株式会社 编辑:程序博客网 时间:2024/04/28 02:21
二分搜索法:
public class BinarySearch {public static int rank(int key, int[] numList){int lo = 0;int hi = numList.length-1;while(lo <= hi){int mid = lo +(hi-lo)/2;if(key < numList[mid]){hi = mid - 1;}else if(key > numList[mid]){lo = mid + 1;}else return mid;}return -1;}public static void main(String[] args) {int[] numList = {0,1,2,3,4,5,6,7,8,9};for (int i = 0; i < numList.length; i++) {System.out.println(BinarySearch.rank(i, numList));}}}

原创粉丝点击