package javaCodes;
import java.util.Scanner;
public class binary_search_updated {
public static int binary( int arr[], int low, int high, int key)
{
if(low > high)
return -1;
int mid = (low+high)/2;
if(arr[mid] == key)
{
return 1;
}
else if(arr[mid] > key)
{
return binary(arr, low, mid, key);
}
else if(arr[mid] < key)
{
return binary(arr, mid+1, high, key);
}
return key;
}
public static void main(String args[])
{
int[] arr = new int[100];
int key, low=0, n;
System.out.println("enter how many numbers : ");
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
System.out.println("now enter numbers : ");
for(int i=0; i<n; i++)
{
arr[i] = sc.nextInt();
}
System.out.println("now enter search key : ");
key = sc.nextInt();
int number = binary(arr, low, n-1, key);
if(number==1)
{
System.out.println("Found");
}
else
{
System.out.println("not found");
}
}
}
Sunday, March 6, 2022
Binary search implementation in Java
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment