ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Java Source Code: Binary Search in Recursion

Updated on November 1, 2013

Get A Website Plus a Free Domain Name in Just 1 Hour!

Bring the new technology in your hands! Share your skills, improve and impress. Get Your Own Website and a Free Domain Name Here!

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 //Example of Java Class
{
	//biSearch is an example of a method or a function
    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;
    }
//this is also a class method
 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(); //this is how to instantiate an object to access a class
        System.out.println("The sorted numbers are: ");
        access.sort(x);//this is how to access a method
        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)); //how to access a class
    }

}

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

facebook.com via google image
facebook.com via google image

Do You Love Java?

See results

Comments

    0 of 8192 characters used
    Post Comment

    • aisha91 profile imageAUTHOR

      Rasna Aisha 

      6 years ago from Manila, Philippines

      Hi payal;

      I'm so sorry for the pause, numbers are sorted in binary search mainly because it is what binary search is. The algorithm of binary search is to sort the numbers first so that it can determine the middle value of the input numbers and the index that holds it. When the value is determined and its index, it would then be use as a comparison to determine the index of the search number. To understand more about what I am talking about, please review again and trace the codes above :D

    • profile image

      payal 

      6 years ago

      thanks for sharing your knowledge...

      but why the numbers must be sorted for binary search?

      please answer me...

    • aisha91 profile imageAUTHOR

      Rasna Aisha 

      6 years ago from Manila, Philippines

      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...^_^

    • hillymillydee profile image

      hillymillydee 

      6 years ago from Canada

      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.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)