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

ALGORITHM 3.2 Binary search (in an ordered array)

时间:2018-06-07 22:55:06      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:binary   get   sea   show   OLE   ctrl   color   ring   empty   

//二分搜索

import edu.princeton.cs.algs4.*;

public class BinarySearchST<Key extends Comparable<Key>, Value>
{
    private Key[] keys;
    private Value[] vals;
    private int N;
    
    public BinarySearchST(int capacity)
    {
        keys = (Key[]) new Comparable[capacity];
        vals = (Value[]) new Object[capacity];
    }
    
    public int size()
    {
        return N;
    }
    
    public Value get(Key key)
    {
        if(isEmpty()) return null;
        int i = rank(key);
        if(i < N && keys[i].compareTo(key) == 0)
            return vals[i];
        else 
            return null;
    }
    
    public boolean isEmpty()
    {
        return N == 0;
    }
    
    public int rank(Key key)
    {
        int lo = 0; int hi = N - 1;
        while(lo <= hi)
        {
            int mid = lo + (hi - lo) / 2;
            int cmp = key.compareTo(keys[mid]);
            if(cmp < 0) hi = mid - 1;
            else if(cmp > 0) lo = mid + 1;
            else return mid;
        }
        return lo;
    }
    
    public void put(Key key, Value val)
    {
        int  i = rank(key);
        if(i < N && keys[i].compareTo(key) == 0)
        {
            vals[i] = val;
            return;
        }
        for(int j = N; j > i; j--)
        {
            keys[j] = keys[j-1];
            vals[j] = vals[j-1];
        }
        keys[i] = key;
        vals[i] = val;
        N++;
    }
    
    public void show()
    {
        for(int i = 0; i < N; i++)
        {
            StdOut.println(keys[i] + " " + vals[i]);
        }
    }
    
    public static void main(String[] args)
    {
        int capacity = 20;
        BinarySearchST<String, Integer> st = new BinarySearchST<String, Integer>(capacity);
        
        while(!StdIn.isEmpty())//CTRL + d
        {
            String key = StdIn.readString();
            Integer num = StdIn.readInt();
            st.put(key, num);
        }
        
        st.show();
    }
}

 

ALGORITHM 3.2 Binary search (in an ordered array)

标签:binary   get   sea   show   OLE   ctrl   color   ring   empty   

原文地址:https://www.cnblogs.com/w-j-c/p/9153031.html

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