Skip to content

Latest commit

 

History

History
27 lines (22 loc) · 437 Bytes

折半查找.md

File metadata and controls

27 lines (22 loc) · 437 Bytes

#折半查找

基本原理:每次查找都对半分,但要求数组是有序的

public class Solution {

	public static int BinarySearch(int[] sz,int key){
		int low = 0;
		int high = sz.length - 1;
		
		while (low <= high) {
			int middle = (low + high) / 2;
			if(sz[middle] == key){
				return middle;
			}else if(sz[middle] > key){
				high = middle - 1;
			}else {
				low = middle + 1;
			}
		}
		return -1;
	}
}