0% found this document useful (0 votes)
1 views

Binary Search

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Binary Search

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Linear Search

Linear Search in Java is a straightforward algorithm that sequentially checks each element of an array
until the target value is found or the end of the array is reached. It has a time complexity of O(n), making
it less efficient than binary search for large datasets.

package Eo;
import java.util.Scanner;
public class Ls {

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner s=new Scanner( System.in);
int a[]= {1,2,3,4,5,34,78};
System.out.println("Enter any nymber to search");
int itm=s.nextInt();
int temp=0;
for(int i=0;i<=a.length-1;i++)
{
if(a[i]==itm)
{
System.out.println("ITEM FOUND IN INDEX NUMBER :"+i);
temp=temp+1;
}

}
if(temp==0)
{

System.out.println("item not found");

OP

Enter any nymber to search


2
ITEM FOUND IN INDEX NUMBER :1

Enter any nymber to search


9
item not found

Binary Search
Binary Search in Java is an efficient algorithm for finding a target value within a sorted array by
repeatedly dividing the search interval in half. It runs in O(log n) time complexity, making it faster than
linear search for large datasets.

EX:

package Eo;
import java.util.Scanner;

public class Bs {

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner s=new Scanner( System.in);
int arr[]= {1,2,3,4,5,6};
System.out.println("Enter any nymber to search");
int itm=s.nextInt();
int li=0,hi=arr.length-1,mi=(li+hi)/2;
while(li<=hi)
{
if(arr[mi]==itm)
{
System.out.println("Item is found in :"+mi);
break;
}
else if(arr[mi]<itm){
li=mi+1;

}
else {
hi=mi-1;

}
mi=(li+hi)/2;

}
if(li>hi)
{
System.out.println("Item not found");

}
OP

Enter any nymber to search


8
Item not found

Enter any nymber to search


2
Item is found in :1

You might also like