码迷,mamicode.com
首页 > 其他好文 > 详细

page61-将二分查找重写为一段面向对象的程序

时间:2014-10-02 14:05:02      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   ar   java   for   数据   sp   

1 将二分查找重写为一段面向对象的程序 (用于在整数集合中进行查找的一种抽象数据类型)

 

public class StaticSETofInts 【API】

  StaticSETofInts(int[] a )根据 a[]中的所有值创建一个集合

  boolean contains(int key) key是否存在于集合中。

【数据实现】

import java.util.Arrays;

public class StaticSETofInts {
    
    private int[] a;
    public StaticSETofInts(int[] keys){
        
        a = new int[keys.length];
        for (int i = 0; i < keys.length; i++) 
            a[i] = keys[i];//保护性复制
        Arrays.sort(a);
    }

    public boolean contains(int key){
        return  rank(key) != -1;
    }
    
    private int rank(int key){//二分查找
        
        int low = 0;
        int high = a.length -1;
        while(low <= high){ //要么存在于a[low..high]中, 要么不存在。
            
            int mid = (low + high) /2;
            if(key < a[mid]) high = mid -1;
            else if(key > a[mid]) low  = mid + 1;
            else return mid;
        }
        return -1;
    }
}

 

【典型测试用例】

public class Whitelist {
    
    public static void main(String[] args) {
        
        int[] w = new In(args[0]).readAllInts();
        StaticSETofInts set = new StaticSETofInts(w);
        
        while(!StdIn.isEmpty()){
            int key = StdIn.readInt();
            if(!set.contains(key)) System.out.println(key);
        }
    }
}

【打印结果】

bubuko.com,布布扣

 

page61-将二分查找重写为一段面向对象的程序

标签:style   blog   http   color   ar   java   for   数据   sp   

原文地址:http://www.cnblogs.com/pacoson/p/4003945.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!