Algorithm-8. Binary Search in an ordered array, binary search in an algorithm Array

Source: Internet
Author: User

Algorithm-8. Binary Search in an ordered array, binary search in an algorithm Array

1. Specific Algorithms

/*** Algorithm 3.2 binary search (based on ordered array) * Created by huazhou on. */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 boolean isEmpty () {return size () = 0;} public Value get (K Ey key) {if (isEmpty () {return null;} int I = rank (key); if (I <N & keys [I]. compareTo (key) = 0) {return vals [I];} else {return null;} public int rank (Key key) {int lo = 0, 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;} // The search key. If it is found, the value is updated. Otherwise, a new public void p element is created. Ut (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 delete (Key key) {if (isEmpty () return; // compute rank int I = rank (key ); // key not in table if (I = N | keys [I]. compareTo (key )! = 0) {return;} for (int j = I; j <N-1; j ++) {keys [j] = keys [j + 1]; vals [j] = vals [j + 1];} N --; keys [N] = null; // to avoid loitering vals [N] = null; // resize if 1/4 full if (N> 0 & N = keys. length/4) resize (keys. length/2 );}}

The implementation of this symbol table uses two arrays to save keys and values. Like the array-based stack, the put () method moves all the larger keys backward one cell before inserting new elements.

The rank () method implements the classical algorithm described in the text to calculate the number of keys smaller than the given key. It first compares the key with the intermediate key. If the key is equal, its index is returned. If the key is smaller than the intermediate key, it is searched in the left half. If the key is greater than the intermediate key, it is searched in the right half.

public Key min(){        return keys[0];    }    public Key max(){        return keys[N-1];    }    public Key select(int k){        return keys[k];    }    public Key ceiling(Key key){        int i = rank(key);        return keys[i];    }    public Key floor(Key key){        int i = rank(key);        if (i < N && key.compareTo(keys[i]) == 0) return keys[i];        if (i == 0) return null;        else return keys[i-1];    }    public boolean contains(Key key) {        return get(key) != null;    }    public Iterable<Key> keys(Key lo, Key hi){        Queue<Key> q = new Queue<Key>();        for (int i = rank(lo); i < rank(hi); i++){            q.enqueue(keys[i]);        }        if(contains(hi)){            q.enqueue(keys[rank(hi)]);        }        return q;    }

2. Algorithm Analysis

The Recursive Implementation of rank () also allows us to immediately come to the conclusion that binary search is very fast, because the recursive relationship can indicate the upper limit of the number of comparisons required by the algorithm.

Proposition:To perform binary search in an ordered array with N keys, a maximum of (lgN + 1) comparison is required (whether or not the result is successful ).

Proof:The analysis here is similar to the analysis of Merge Sorting (but relatively simple ). Set C (N) to the number of times a key needs to be compared in the symbol table with the size of N. Obviously we have C (0) = 0, C (1) = 1, and for N> 0, we can write an inductive relationship directly corresponding to the recursive method:

C (N) <= C (random N/2 random) + 1

No matter whether the search continues on the left or right of the intermediate element, the size of the sub-array will not exceed limit N/2 limit, we need a comparison to check whether the intermediate element is equal to the searched key, and decide whether to continue searching for the left-side or right-side sub-array. This recursion is easy when N is a power minus 1 (N = 2n-1) of 2. First, because limit N/2 Limit = 2n-1-1, we have:

C (2n-1) <= C (2n-1-1) + 1

Use this formula to replace the first item on the right of the inequality:

C (2n-1) <= C (2n-2-1) + 1 + 1

Repeat the above step to get The N-2 times:

C (2n-1) <= C (20) + n

The final result is:

C (N) = C (2n) <= n + 1 <lgN + 1

For general N, the exact conclusion is more complex, but it is not difficult to get it through the above arguments. The time required for binary search must be within the logarithm range.

Although it can ensure that the time required for searching is at the logarithm level, BinarySearchST still cannot support us to use programs similar to FrequencyCounter to handle large problems, because the put () method is still too slow. Binary Search reduces the number of comparisons but does not reduce the running time, because it cannot change the following fact:

When keys are randomly arranged, the number of times an array needs to be accessed to construct an ordered array-based symbol table is the square level of the array length (although the key arrangement is not random in actual conditions, but it still fits well with this model ).

Proposition:Insert a new element into an ordered array of N in the worst case ~ Therefore, to insert N elements into an empty symbol table, you need to access ~ N2 frequency group.

Proof:Same as the proposition.

3. Summary

In general, binary lookup is much faster than sequential lookup. It is also the best choice for many practical applications. Of course, binary search is not suitable for many applications. For example, it cannot process the Leipzig mongoa database, because the search and insert operations are mixed, and the symbol table is too large. As we have emphasized, modern applications need to support efficient searching and inserting symbol tables at the same time. That is to say, we need to be able to insert (or delete) any key-value pairs while constructing a large symbol table, and also to complete the search operation.

 

Source code download]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.