Binary Search Program in java || Explain with logic in simple way|| by Er prince Kumar Ojha
1. Write a program to find the binary search
Method:1
class BinaryS
{
public static void main(String[] args)
{
int arr[]={2,3,4,5,6,7,8};
int search=5;
int first=0;
int last=arr.length-1;
int mid=(first+last)/2;
while(first<=last){
if(arr[mid]<search){
first=mid+1;
}
else if(arr[mid]==search){
System.out.println("Number is found:"+mid);
break;
}
else{
last=mid-1;
}
mid=(first+last)/2;
}
if(first>last)System.out.println("Number is not found:");
}
}
==================================
6.Write a program to implement of Binary search
Method 1:
import java.util.Scanner;
import java.util.Arrays;
class Binary{
//Binary Search Implementation in java
public static void binarySearch(int []arr,int first,int last,int search){
int mid=(first+last)/2;
while(first<=last){
if(arr[mid]<search){
first=mid+1;
}
else if(arr[mid]==search){
System.out.println("Number is found At position:"+mid);
break;
}
else{
last=mid-1;
}
mid=(first+last)/2;
}
if(first>last){
System.out.println("Number is not Found in this Array:");
}
}
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int arr[]=new int[5];
System.out.println("Enter the "+5+" Element in Array:");
for(int i=0;i<arr.length;i++){
arr[i]=sc.nextInt();
}
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
int first=0;
int last=arr.length-1;
System.out.println("Enter the Search Values:");
int search=sc.nextInt();;
binarySearch(arr,first,last,search);
}
}
Method 2:
class BinaryS
{
public static void main(String[] args)
{
int arr[]={2,3,4,5,6,7,8};
int search=5;
int first=0;
int last=arr.length-1;
int mid=(first+last)/2;
while(first<=last){
if(arr[mid]<search){
first=mid+1;
}
else if(arr[mid]==search){
System.out.println("Number is found:"+mid);
break;
}
else{
last=mid-1;
}
mid=(first+last)/2;
}
if(first>last)System.out.println("Number is not found:");
}
}
Comments
Post a Comment