Home > DeveloperSection > Blogs > Binary Search using Recursion in java

Binary Search using Recursion in java


Java Java 
Ratings:
0 Comment(s)
 1806  View(s)
Rate this:

Binary Search using Recursion in java

In this blog I am provide you the code for Binary search using Recursion in java.

import java.io.*;

public class MyRecursiveBinarySearch {

                public static int recursiveBinarySearch(int[] sortedArray, int start, int end, int key) {  

                    if (start < end) {

                        int mid = start + (end - start) / 2; 

                        if (key < sortedArray[mid]) {

                            return recursiveBinarySearch(sortedArray, start, mid, key);

                           

                        } else if (key > sortedArray[mid]) {

                            return recursiveBinarySearch(sortedArray, mid+1, end , key);

                           

                        } else {

                            return mid;  

                        }

                    }

                    return -(start + 1);

           

                }

                public static void main(String[] args) {

                               

                               

                                System.out.print("Enter the lenth of array : ");

                                int len= Integer.parseInt(System.console().readLine());

                                int[] arr1 = new int[len];

                                for(int i=0;i<len;i++)

                                {

                                                System.out.print("Enter element ["+i+"] postion : ");

                                                arr1[i]= Integer.parseInt(System.console().readLine());

                                }

                                System.out.println("Your values are\n");

                                for(int i=0;i<len;i++)

                                {

                                                System.out.print(arr1[i]+"\t");

                                               

                                }

                                System.out.println();

                                System.out.print("Enter value for search -: ");

                                int find= Integer.parseInt(System.console().readLine());

                                int index = recursiveBinarySearch(arr1,0,arr1.length,find);

                if(index == -1)

                                {

                                                System.out.println("Given value not found in array!");

                                }

                                else

                                 {

                                                System.out.println("Value "+find+" found at "+index+" position.");

                                 }

                }

}


Don't want to miss updates? Please click the below button!

Follow MindStick