Binary Search Using Recursion in java


public class binarySearch
{

    public int binSearch(int[] arr, int fIndex, int lIndex,int search)
    {

int middle = (fIndex + (lIndex - fIndex) / 2);

  if(fIndex<lIndex ){

   if (search == arr[middle]){

    return middle;
   }

   else if(search < arr[middle]){
    if(search == arr[0])
     return 0;
    return binSearch(arr, fIndex, middle, search);
   }

   else if(search > arr[middle]){
    if(search == arr[middle+1])
     return middle + 1;
    return binSearch(arr, middle+1, lIndex, search);
   }

  }
    return -1;
    }

 public void sort(int[] arr)
{
       for(int i=0; i<arr.length; i++)
        {
            for(int j=i+1; j<arr.length; j++ )
            {
                if(arr[i] > arr[j])
                {
                    int temp = arr[j];
                    arr[j]=arr[i];
                    arr[i]= temp;
                }
            }
        }

       for(int i=0; i<arr.length; i++)
       {
           System.out.print(arr[i] + " ");
       }
}

}

//main class


import java.util.Scanner;

public class Main {

    public static void main(String[] args)
    {
         Scanner input = new Scanner(System.in);

        System.out.print("Enter the size of the array: ");
        int n = input.nextInt();
        int[] x = new int[n];

        System.out.print("Enter "+ n +" numbers: ");
        int middle;
        for(int i=0; i<n; i++)
        {
            x[i] = input.nextInt();
        }

        binarySearch access = new binarySearch();
        System.out.println("The sorted numbers are: ");
        access.sort(x);
        System.out.println();
        
        System.out.print("Enter the number you want to search: ");
        int value = input.nextInt();

        System.out.print("The search number is on the index ");
        System.out.print(access.binSearch(x, 0, x.length-1, value));
    }

}

0 comments:

Post a Comment

 
 
 
 


Copyright © 2012 http://codeprecisely.blogspot.com. All rights reserved |Term of Use and Policies|