ALGORITHM 3.2 Binary search (in an ordered array)

Posted w-j-c

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ALGORITHM 3.2 Binary search (in an ordered array)相关的知识,希望对你有一定的参考价值。

//二分搜索

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)的主要内容,如果未能解决你的问题,请参考以下文章

[Algorithms] Binary Search Algorithm using TypeScript

[Algorithm] 7. Serialize and Deserialize Binary Tree

2 - Binary Search & LogN Algorithm

3.2 Lowest Common Ancestor of a Binary Tree(LeetCode 236)

[Algorithm] Delete a node from Binary Search Tree

[Algorithm] 94. Binary Tree Inorder Traversal iteratively approach