Skip navigation links
net.sf.kdgcommons.collections

Class BinarySearch

    • Constructor Detail

      • BinarySearch

        public BinarySearch()
    • Method Detail

      • search

        public static <T> int search(BinarySearch.Accessor<T> accessor,
                                     T value)
        Searches a sorted array-like structure using the provided Accessor. If the object is found, the returned value will be the object's location within that structure.

        If the object is not found, the value of the returned insertion point will depend on the accessor's defined range. If the accessor's range covers the entire structure, or if the object would appear within the defined range, then the returned insertion point will indicate the position where the object should be inserted. If the accessor covers a subset of the structure, and the missing object would appear outside that structure, then the insertion point will be just before or just after the defined range, not the absolute position in the array.

        This is best illustrated with examples. Given the array ['B', 'D', 'F', 'H', 'J', 'L', 'N', 'P', 'R']:

        • A search for the value 'C', covering the entire range, would return -2. This is the same behavior as the JDK's built-in searches.
        • A search for the value 'C', covering elements 2..4, would return -3. This is because the search doesn't know of any values outside the range, so it would indicate that the value should be inserted just before the range.
        • A search for the value 'B', covering the elements 2..4, would also return -3. Although 'B' appears in the complete array, it is not in the search range. And, like 'C', the search only knows that it should be inserted before the range.
        • A search for the value 'F', covering the elements 2..4, could return +2.
        • A search for the value 'G', covering the elements 2..4, would return -4. This insertion point is within the range being searched, so is accurate.
        • A search for the value 'J', covering the elements 2..4, would return -5. This is because, although the value of element 4 is 'J', the upper bound of the range is exclusive. So the search can't find the value, and reports that it would be inserted after the range.
        • A search for the value 'L', covering the elements 2..4, would also return -5, indicating that the value could not be found within the bounds of the search (even though it exists outside those bounds).
      • search

        public static <T> int search(int[] index,
                                     T value,
                                     BinarySearch.IndexedComparator<T> cmp)
        Searches sorted array of indexes into some other array-like object (which does not need to be sorted). Returns the position/insertion point of the requested value within the index array.