BinarySearch(二分查詢)

a2459956664發表於2016-10-04
//二分查詢
package Algorithms;

import java.util.Arrays;

import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;

public class P28_BinarySearch {

	public static int rank(int key, int[]a){
		//資料必須是有序的
		int lo = 0;
		int hi = a.length - 1;
		while (lo <= hi){
			//被查詢的鍵值要麼不存在,要麼必然存在於a[lo..hi]之中
			int mid = lo + (hi - lo) / 2;
			if (key < a[mid]){
				hi = mid - 1;
			}
			else if (key > a[mid]){
				lo = mid + 1;
			}
			else{
				return mid;
			}
		}
		return -1;
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		In in = new In(args[0]);
		int[] whitelist = in.readAllInts();
		Arrays.sort(whitelist);
		while (!StdIn.isEmpty()){
			//讀取鍵值,如果不存在於白名單中則將其列印
			int key = StdIn.readInt();
			if (rank(key, whitelist) < 0){
				StdOut.println(key);
			}
		}
	}
}

相關文章