Recursive Binary Search - Java Data Structure

Java examples for Data Structure:Search

Introduction

Checks whether an integer(key) exists in a sorted array and returns the index of the key (if found) and -1 (if not found)

Demo Code



import java.util.*;
public class Binary_recursive{
    private int size;
    private int[] arr;
    private int key;

    private int search( int min, int max )
    {// ww w  .ja v a 2 s. c o m
        int mid;
        if ( min <= max ) {
            mid = middle( min, max );
            if( this.arr[mid] == this.key ){
                return mid;
            }
            else if ( this.arr[mid] < this.key ) {
                min = mid + 1;
                return this.search( min, max );
            }
            else{
                max = mid - 1;
                return this.search( min, max );
            }
        }
        return -1;
    }

    private int middle( int min, int max )
    {
        int sum = min + max; 
        if ( sum%2 == 0 )
        {
            return sum/2;
        }
        else
        {
            return (sum/2)+1;
        }
    }

    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        int i,result;
        
        Binary_recursive InputArray = new Binary_recursive();
    
        System.out.print("Size of array = ");
        InputArray.size = in.nextInt();

        InputArray.arr = new int[InputArray.size];

        System.out.println("Enter the integers in the array : ");
        for ( i=0; i<InputArray.size; i++ ) {
            InputArray.arr[i] = in.nextInt();
        }

        System.out.print("Enter the integer to be searched : ");
        InputArray.key = in.nextInt();

        result = InputArray.search( 0, InputArray.size-1 );

        if ( result < 0 ) {
            System.out.println("Integer "+InputArray.key+" not found in the Input Array");
        }
        else {
            System.out.println("Integer "+InputArray.key+" found at index position = "+result+" in the Input Array");
        }
    }

}

Related Tutorials