CSDN博客

img programs

折半查找

发表于2008/9/30 20:49:00  385人阅读

import java.util.Arrays;
import java.util.Random;

public class BinSearch {

	public static int search(int key, int[] a) {
		return search(key, a, 0, a.length);
	}

	private static int search(int key, int[] a, int left, int right) {
		while (left <= right) {
			final int mid = (left + right) >>> 1;
			if (a[mid] > key) {
				right = mid - 1;
			} else if (a[mid] < key) {
				left = mid + 1;
			} else {
				return mid;
			}
		}
		return -1;
	}

	public static void main(String[] args) {
		final int key = 6;
		final int N = 10;
		int[] a = new int[N];
		Random random = new Random();
		for (int i = 0; i < a.length; i++) {
			a[i] = random.nextInt(N << 1);
		}
		Arrays.sort(a);
		System.out.println(Arrays.toString(a));
		System.out.println(search(key, a));
		System.out.println(Arrays.binarySearch(a, key));
	}
}


0 0

相关博文

我的热门文章

img
取 消
img