FileDocCategorySizeDatePackage
BinarySearch.javaAPI DocAndroid 1.5 API2334Wed May 06 22:41:04 BST 2009org.apache.harmony.luni.util

BinarySearch

public class BinarySearch extends Object

Fields Summary
Constructors Summary
Methods Summary
public static intbinarySearch(java.lang.String data, char value)
Search the sorted characters in the string and return an exact index or -1.

param
data the String to search
param
value the character to search for
return
the matching index, or -1

        int low = 0, high = data.length() - 1;
        while (low <= high) {
            int mid = (low + high) >> 1;
            char target = data.charAt(mid);
            if (value == target)
                return mid;
            else if (value < target)
                high = mid - 1;
            else
                low = mid + 1;
        }
        return -1;
    
public static intbinarySearchRange(java.lang.String data, char c)
Search the sorted characters in the string and return the nearest index.

param
data the String to search
param
c the character to search for
return
the nearest index

        char value = 0;
        int low = 0, mid = -1, high = data.length() - 1;
        while (low <= high) {
            mid = (low + high) >> 1;
            value = data.charAt(mid);
            if (c > value)
                low = mid + 1;
            else if (c == value)
                return mid;
            else
                high = mid - 1;
        }
        return mid - (c < value ? 1 : 0);