Flag This Hub

Java Source Code: Binary Search in Recursion

By


Below is the java source code for a recursive binary search. The program requires to sort the numbers first in an ascending order before the binary search can be implemented successfully. Basically, what the program does is prompt the user to input the size of the array, enter the numbers that the user wants, sort it, then ask for the number he wants to search. If the number is on the array, it outputs the index of the array where it is located but if it is not on the list is simple returns -1.Here how the program works.

How the program works

Important note: Binary Search algorithm would work only if the numbers are sorted.

For example:

User's enters: 2 1 3 5 4

The sorted numbers are: 1 2 3 4 5

Search number: 2

The numbers is on the array index 1, since array index starts from 0. if the search number is 6, then the program returns -1, since 6 is not on the list.

How Binary Search Works?

1. It computes the middle index of the array

From the given numbers above, since there are 5 numbers, we will divide it into 2 to get the middle.

middle = 5/2, returns 2, since they are both integers so any decimal value will not be counted.

meaning on: 1 2 3 4 5, 3 is the middle, Since array index starts from 0.

2. Compare if the search number is equal to the middle if, yes return the index middle.

if(middle == search)

return index middle.

3. If not, it then compare if the search number is greater than or less than the middle. if it is greater than the value of the middle, the search starts at the middle + 1 number till at the last number in the array, however if the search number is less than the middle, it compares next the number located on the middle - 1 index value up to the first value of the array.

The Source code is given below.


Java Source code: How to implement Binary Search Using Recursion.

//Java Class


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));
    }

}

Available Java E-books

Computer Programming for Teens (For Teens (Course Technology))
Amazon Price: $15.00
List Price: $29.99
Introduction to Java Programming, Comprehensive (8th Edition)
Amazon Price: $75.00
List Price: $137.00
Murach's Java Programming
Amazon Price: $35.00
List Price: $57.50

Sample Output 1:

Enter the size of the array: 5

Enter 5 numbers: 2 1 3 5 4

The sorted numbers are:

1 2 3 4 5

Enter the number you want to search: 3

The search number is on the index 2

Sample Output 2:

Enter the size of the array: 5

Enter 5 numbers: 3 2 1 4 5

The sorted numbers are:

1 2 3 4 5

Enter the number you want to search: 1

The search number is on the index 0

Sample Output 3:

Enter the size of the array: 5

Enter 5 numbers: 2 1 3 5 4

The sorted numbers are:

1 2 3 4 5

Enter the number you want to search: 6

The search number is on the index -1


Want More Java Source Codes? Choose sample codes below.

Or Perhaps, You may want to read these hubs.

Comments

hillymillydee 3 months ago

Aisha,

I see you have unique topic, I am not good in java source code but I know many people in the search engine will look for your articles. They are very useful that's why I followed you because I want to read more of your hubs.

You are doing really well in Hubpages. I can see you will have a successful experience here.

Thanks for sharing your knowledge.

aisha91 3 months ago

Hi hillymillydee,

Nah thanks for stopping by and for commenting, You are thoughtful hilly, you belong to those who inspires me...:)

Always have a great day and happy writing...^_^

payal 5 days ago

thanks for sharing your knowledge...

but why the numbers must be sorted for binary search?

please answer me...

Submit a Comment
Members and Guests

Sign in or sign up and post using a hubpages account.



    Like this Hub?
    Please wait working