欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

二分查找

程序员文章站 2022-05-08 19:12:56
...

二分查找也称折半查找(Binary Search),它是一种效率较高的查找方法。但是,折半查找要求线性表必须采用顺序存储结构,而且表中元素按关键字有序排列。(百度百科:https://baike.baidu.com/item/二分查找/10628618?fr=aladdin)


public class Test{

	public static void main(String[] args) {

		int src[] = {1, 3, 4, 5, 7, 17, 20, 22, 50};
		for (int a : src) {
			System.out.print(a + ", ");
		}
		System.out.println();
		int dst = new Test().binarySearch(src, 5);
		System.out.println(dst);
		
	}
	
	public int binarySearch(int src[], int dst) {
		int count = src.length;
		int start = 0;
		int end = src.length;
		while(start!= count - 1 && end != 0) {
			int middle = (start + end) / 2;
			if (src[middle] > dst) {
				end = middle;
			} else if (src[middle] < dst) {
				start = middle;
			} else {
				return middle;
			}
		}
		
		// when not existed
		return -1;
	}
}