CodesJava

Easy learning with example program codes

Java binary search program using recursion

Example

package com.codesjava;
 
public class Test {
    public static int binarySearch(int[] data,int start, int end,int key){    
        if (start < end) {
            int mid = start + (end - start) / 2;  
            if (key < data[mid]) {
                return binarySearch(data, start, mid, key);
 
            } else if (key > data[mid]) {
                return binarySearch(data, mid+1, end , key);
 
            } else {
                return mid;   
            }
        }
        return -(start + 1);    
    }    
 
    public static void main(String args[]){
	int[] data= {50,127,130,150,170,910,1009};    
        int key = 130;    
        System.out.println(key+" is found at index: "+binarySearch(data,0, data.length, key));  
   }
}

Output

130 is found at index: 2
Please follow and like us:
error








Copyright © 2019 CodesJava DMCA.com Protection Status