1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| import java.util.*;
public class binarySearchRecursive { public static int binarySearchRecursive(int[] arr, int start, int end, int hkey) { if (start > end) { return -1; } int mid = start + (end - start)/2; if(arr[mid] > hkey){ return binarySearchRecursive(arr, start, mid-1,hkey); } if (arr[mid] < hkey){ return binarySearchRecursive(arr, mid+1, end,hkey); } return mid; }
public static void main(String[] args){ int[] arr = {1,2,4,6,7}; int result = binarySearchRecursive(arr,0,arr.length-1,4); System.out.println("result = " + result); } }
|