java实现的折半查找

/**
 * 折半查找
 * author: zcl
 */
public class BinarySearch {

	public static int search(int[] arrays, int target) {
		
		int start = 0;
		int end = arrays.length - 1;
		int pos;
		while (start <= end) {
			pos = (start + end) / 2;
			if (arrays[pos] == target) {
				return pos;
			} else if (arrays[pos] > target) {//如果数组中间的数大于目标,则将end的位置变成数组中间位置-1的位置
				end = pos - 1;
			} else {
				start = pos + 1;//如果数组中间的数小于目标,则将start的位置变成数组中间位置+1的位置
			}
		} 
		return -1; //若没有查找到,则返回-1
	}
	
	public static void main(String[] args) {
		int[] arrays = {2,3,28,39,59,288,322,324,2323};
		System.out.println(search(arrays, 28));
		System.out.println(search(arrays, 322));
		System.out.println(search(arrays, 59));
		System.out.println(search(arrays, 288));
	}
}

 

你可能感兴趣的:(java)