How to search an element in sorted array in java

0





In this blog we will how to search an element in an array in a sorted array using binary search. 

We are given a sorted array and a number num we have to find out whether the number is present in the array or not. To solve this problem we will use binary search technique .


There are two solutions for this problem.

1. Using Iteration :

public class Binaryiter {
public static boolean binaryitersearch(int []arr , int val)
{
int low=0,high=arr.length-1;
while(low<=high)
{
int mid=(low+high)/2;
if(val==arr[mid])
return true;
else
{
if(val>arr[mid])
low=mid+1;
else
high=mid-1;
}
}
return false;

}
public static void main(String args[]){
int arr[]={45,85,25,61,13,29,43,72,55,39};
System.out.println(binaryitersearch(arr,72));
}
}



2. Using Recursion :



public class BinaryRec {
public static boolean binaryrecsearch(int []arr,int low,int high , int val)
{
int mid=(low+high)/2;
if(arr[mid]==val)
return true;
if(arr[mid]>val)
return binaryrecsearch(arr,low,mid-1,val);
else{
if(arr[mid]<val)
return binaryrecsearch(arr,mid+1,high,val);
}
return false;
}
public static void main(String args[]){
int arr[]={45,85,25,61,13,29,43,72,55,39};
int low=0,high=arr.length-1;
System.out.println(binaryrecsearch(arr,low,high,2));
}
}


 

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !