You are on page 1of 2

Binary search and linear search

Anuj Gupta 20BCE7055

import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int []a=new int[100000];
System.out.println("Enter the number of element you want to insert");
int n=sc.nextInt();
System.out.println("Enter the "+n+" elements\n !!Warning!! Enter the
elements in ascending order");
for(int i=0;i<n;i++){
a[i]=sc.nextInt();
}
int first=a[0];
int last=a[n-1];
int ch;
while(true){
System.out.println("Enter the element you want to search");
int key=sc.nextInt();
System.out.println("Enter your choice...\n 1. Linear search\n
2. Binary search");
ch=sc.nextInt();
switch(ch){
case 1: Linearsearch(a,key);
break;

case 2: Binarysearch(a,first,last,key);
break;

case 3: System.exit(0);
break;

default : System.out.println("Invalid choice");


break;
}
}
}

static void Linearsearch(int a[],int key){


int i=0;
for(i=0;i<a.length;i++){
if(key==a[i]){
int j=i+1;
System.out.println(key+" is found at "+j);
break;}
else{
if(i==a.length-1)
System.out.println(key+" is not found");
}
}
}

static void Binarysearch(int a[],int first,int last,int key){


int mid=(first+last)/2;
while(first<=last){
if (a[mid]<key){
first=mid+1;
}else if(a[mid]==key){
System.out.println(key+" is found at " + mid);
break;
}else{
last=mid-1;
}
mid=(first+last)/2;
}
if ( first>last ){
System.out.println("Element is not found!");
}
}
}

You might also like