binary search in java
binary search in java
code :
public static int bSearch(int arr[] ,int key){
int f = 0;
int l = arr.length;
while(f<=l){
int mid = (f+l)/2;
if(arr[mid] == key){
return mid;
}
else if(arr[mid] < key){
f = mid +1;
}
else{
l = mid-1;
}
}
return -1;
}
public static void main(String[] args) {
int arr [] = {34,32,43,45,65,67};
int key = 45;
int index = bSearch(arr,key);
if(index == -1){
System.out.println("not found");
}else{
System.out.println("find index no of array is : " + index);
}
}
}
find index no of array is : 3
code:
class HelloWorld {
public static int bSearch(int arr[] ,int key){
int f = 0;
int l = arr.length;
while(f<=l){
int mid = (f+l)/2;
if(arr[mid] == key){
return mid;
}
else if(arr[mid] < key){
f = mid +1;
}
else{
l = mid-1;
}
}
return -1;
}
public static void main(String[] args) {
int arr [] = {34,32,43,45,65,67};
int key = 40;
int index = bSearch(arr,key);
if(index == -1){
System.out.println("not found");
}else{
System.out.println("find index no of array is : " + index);
}
}
}
Output:
not found
binary Search in array
thanks
No comments: