binary serarch code example
Example 1: binary search
import java.util.Scanner;
public class Binarysearch {
public static void main(String[] args) {
int[] x= {1,2,3,4,5,6,7,8,9,10,16,18,20,21};
Scanner scan=new Scanner(System.in);
System.out.println("enter the key:");
int key=scan.nextInt();
int flag=0;
int low=0;
int high=x.length-1;
int mid=0;
while(low<=high)
{
mid=(low+high)/2;
if(key<x[mid])
{
high=mid-1;
}
else if(key>x[mid])
{
low=mid+1;
}
else if(key==x[mid])
{
flag++;
System.out.println("found at index:"+mid);
break;
}
}
if(flag==0)
{
System.out.println("Not found");
}
}
}
Example 2: binary search
#include <iostream>
using namespace std;
void binarysearch(int arr[],int start,int end,int val)
{
if(start<end)
{
int mid=(start+end)/2;
if(arr[mid]==val)
{
cout<<"value found:"<<endl;
}
else if(arr[mid]<val)
{
binarysearch(arr,mid+1,end,val);
}
else if(arr[mid]>val)
{
binarysearch(arr,start,mid-1,val);
}
}
else
{
cout<<"not present:"<<endl;
}
}
int main()
{
int n;
cout<<"enter the size of the array:"<<endl;
cin>>n;
int arr[n];
cout<<"enter the elements of the array:"<<endl;
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
cout<<"enter the value you want to search:"<<endl;
int val;
cin>>val;
binarysearch(arr,0,n-1,val);
return 0;
}
Example 3: binary search
import java.util.*;
public class BinarySearch {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] a = {10,20,50,30,40};
int key=sc.nextInt();
Arrays.sort(a);
int first=0,end=a.length-1,mid=0,flag=0;
while(first<=end)
{
mid=(first+end)/2;
if(key<a[mid])
{
end = mid-1;
}
else if(key>a[mid])
{
first = mid+1;
}
else
{
flag=1;
break;
}
}
if(flag==1)
{
System.out.println("Success! found");
}
else
{
System.out.println("Error! This key (" + key + ") does not exist in the array");
}
}
}