class KeySearch {

    static <KEY,VALUE> int search( PageCursor cursor, TreeNode<KEY,VALUE> bTreeNode, TreeNode.Type type, KEY key,
            KEY readKey, int keyCount )
    {
        if ( keyCount == 0 )
        {
            return searchResult( 0, false );
        }

        int lower = 0;
        int higher = keyCount - 1;
        int pos;
        boolean hit = false;

        // Compare key with lower and higher and sort out special cases
        Comparator<KEY> comparator = bTreeNode.keyComparator();
        int comparison;

        // key greater than greatest key in node
        if ( comparator.compare( key, bTreeNode.keyAt( cursor, readKey, higher, type ) ) > 0 )
        {
            pos = keyCount;
        }
        // key smaller than or equal to smallest key in node
        else if ( (comparison = comparator.compare( key, bTreeNode.keyAt( cursor, readKey, lower, type ) )) <= 0 )
        {
            if ( comparison == 0 )
            {
                hit = true;
            }
            pos = 0;
        }
        else
        {
            // Start binary search
            // If key <= keyAtPos -> move higher to pos
            // If key > keyAtPos -> move lower to pos+1
            // Terminate when lower == higher
            while ( lower < higher )
            {
                pos = (lower + higher) / 2;
                comparison = comparator.compare( key, bTreeNode.keyAt( cursor, readKey, pos, type ) );
                if ( comparison <= 0 )
                {
                    higher = pos;
                }
                else
                {
                    lower = pos + 1;
                }
            }
            if ( lower != higher )
            {
                return NO_SUCCESS_FLAG;
            }
            pos = lower;

            hit = comparator.compare( key, bTreeNode.keyAt( cursor, readKey, pos, type ) ) == 0;
        }
        return searchResult( pos, hit );
    }

    private  KeySearch();

}