二分搜索的java源码实践

平常编程中,经常要用到二分搜索。

java JDK中的java.lang.Arrays类中已经实现了二分搜索。

可以方便地在一个已排序好数组中,查找给定的元素。

数组元素可以是byte,int,char,long,float,double等等基本类型。


今天我自己用java实现一次,分别用递归和非递归两种方式实现。java源码如下:

	//非递归实现
	public static String binarySearch2(int[] array, int value) {
		String result = "index of " + value + " is ";
		int low = 0;
		int high = array.length - 1;
		int middle = 0;
		
		while (low <= high) {
			middle = (low + high)>>1;
			if (array[middle] == value) {
				return result + middle;
			} else if (array[middle] < value) {
				low = middle + 1;
			} else {
				high = middle - 1;
			}
		}
		
		return "no such element" + value;
	}
	
	//递归实现
	public static String binarySearchRecursive(int[] array, int start, int end, int value) {
		String result = "index of " + value + " is ";

		if (start <= end) {
			int middle = (start + end)>>1;
			if (array[middle] == value) {
				result += middle;
				System.out.println(result);
				return result;
			} else if (array[middle] < value) {
				return binarySearchRecursive(array, middle + 1, end, value);
			} else {
				return binarySearchRecursive(array, start, middle - 1, value);
			}
		}
		
		return "no such element " + value;
	}
	
	public static void main(String[] args) {
		int[] array = {1,2,3,4,5,6,7,8,9};
		String result = binarySearchRecursive(array, 0, array.length - 1, 3);
		System.out.println(result);
	}

递归实现的结果如下:( 注意递归函数与非递归函数的区别

index of 3 is 2
index of 3 is 2


非递归实现如下:

index of 3 is 2

你可能感兴趣的:(二分搜索)