Created
June 21, 2021 03:06
-
-
Save Ram-1234/b450bc88d45fd76c630b7355cf0d721e to your computer and use it in GitHub Desktop.
Find an Element In a Sorted Array Using Binary Search
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
input: | |
6 | |
5 | |
1 3 5 7 9 11 | |
output: | |
Success #stdin #stdout 0.1s 49484KB | |
element found | |
/* package whatever; // don't place package name! */ | |
import java.util.*; | |
import java.lang.*; | |
import java.io.*; | |
/* Name of the class has to be "Main" only if the class is public. */ | |
class Ideone | |
{ | |
static int eval(int[] a,int f,int s,int key){ | |
int mid=(f+s)/2; | |
while(f<=s){ | |
if(a[mid]==key){ | |
return 1; | |
}else if(key>a[mid]){ | |
return eval(a,mid+1,s,key); | |
}else if(key<a[mid]){ | |
return eval(a,f,mid-1,key); | |
} | |
} | |
return -1; | |
} | |
public static void main (String[] args) throws java.lang.Exception | |
{ | |
Scanner sc=new Scanner(System.in); | |
int s=sc.nextInt(); | |
int key=sc.nextInt(); | |
int arr[]=new int[s]; | |
for(int i=0;i<s;i++){ | |
arr[i]=sc.nextInt(); | |
} | |
int f=0; | |
int result=eval(arr,f,s-1,key); | |
if(result==1){ | |
System.out.println("element found"); | |
}else{ | |
System.out.println("element not found"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment