Binary Search with Recursion.

      No Comments on Binary Search with Recursion.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import java.util.*;
 
public class Tester {
 
   public static int binSearch(int[] a, int value, int start, int end)
   {
       if((end - start) <= 1)//array is 1 or 0
       {
           if(a[start] == value)
               return start;
           if(a[end] == value)
               return end;
           return -1;
       }
 
       int midPoint = (end + start) / 2;
 
       if(a[midPoint] > value)
       {
           return binSearch(a, value, 0, midPoint);
       }
       else
       {
           return binSearch(a, value, midPoint, end);
       }              
 
   }  
 
    public static void main(String[] args) {
 
 
        int[] num = {1,2,3,4,5,6,7,8,9,10};
        System.out.println(Arrays.toString(num));
 
        System.out.println(binSearch(num, 8, 0, num.length-1));
	}
}
Share This!

Leave a Reply

Your email address will not be published.