Recursive binary search method - Java Data Structure

Java examples for Data Structure:Search

Description

Recursive binary search method

Demo Code


//package com.java2s;

public class Main {
    /**//from  w  ww. j a  v a  2s .  co m
     * Recursive binary search method
     * @param items The array being searched
     * @param target The object being searched for
     * @param first The subscript of the first element
     * @param last The subscript of the last element
     * @return The subscript of target if found; otherwise -1.
     */
    private static int binarySearch(Object[] items,
            Comparable<Object> target, int first, int last) {
        if (first > last) {
            return -1; // Base case for unsuccessful search.
        } else {
            int middle = (first + last) / 2; // Next probe index.
            int compResult = target.compareTo(items[middle]);
            if (compResult == 0) {
                return middle; // Base case for successful search.
            } else if (compResult < 0) {
                return binarySearch(items, target, first, middle - 1);
            } else {
                return binarySearch(items, target, middle + 1, last);
            }
        }
    }

    /**
     * Wrapper for recursive binary search method
     * @param items The array being searched
     * @param target The object being searched for
     * @return The subscript of target if found; otherwise -1.
     */
    public static int binarySearch(Object[] items, Comparable<Object> target) {
        return binarySearch(items, target, 0, items.length - 1);
    }
}

Related Tutorials