数组查询

package array;

public class ArrayFind {
	public static void main(String[] args) {
		int[] arr = {13,15,19,28,33,45,78,106};
		int key = 15;
		int index = binarySearch2(arr, key);
		System.out.println(index);
	}

	/*
	 * 数组常见功能:查找
	 */
	public static int getIndex(int[] arr, int key) {
		for (int x = 0; x < arr.length; x++) {
			if (arr[x] == key)
				return x;
		}
		return -1;
	}

	/**
	 * 折半查找(针对有序数组)
	 */
	public static int binarySearch(int[] arr, int key) {
		// 定义三个指针变量。
		int min = 0;
		int max = arr.length - 1;
		int mid = (min + max) / 2;
		// 循环折半,条件, min<=max
		while (key != arr[mid]) {
			// 让被找元素和中间索引元素进行比较
			if (key > arr[mid]) {
				min = mid + 1;
			} else if (key < arr[mid]) {
				max = mid - 1;
			} 
			if(max<min){
				return -1;
			}
			mid = (min + max) / 2;
		}
		return mid;
	}
	
	/**
	 * 折半查找(针对有序数组)
	 */
	public static int binarySearch2(int[] arr, int key) {
		int max,min,mid;
		min = 0;
		max = arr.length-1;

		while(min<=max)
		{
			mid = (max+min)>>1;

			if(key>arr[mid])
				min = mid + 1;
			else if(key<arr[mid])
				max = mid - 1;
			else
				return mid;
		}
		return -1;
	}
}

  

posted @ 2019-08-16 08:12  月落书香  阅读(384)  评论(0编辑  收藏  举报