当前位置:编程学习 > JAVA >>

二分查找

//找不到、数组为空返回-1,否则返回数组下标
public class BinarySearch {
	public static int search(int[] a, int num) {
		if(a==null||a.length==0){
			return -1;
		}
		int low = 0;
		int high = a.length - 1;
		while (low <= high) {
			int mid = (low + high) / 2;
			if (a[mid] == num) {
				return mid;
			} else if(a[mid] > num) {
				high = mid - 1;
			} else {
				low = mid + 1;
			}
		}
		return -1;
	}
	public static void main(String[] args) {
		int[] a = {1,2,3,4,7,8,9,10,12,14};
		System.out.println(search(a,7));
	}
}

 

补充:软件开发 , Java ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,