Binary Search program in java
Program:
import java.util.*;
import java.lang.*;
import java.io.*;
class Test{
public static void main(String[] args){
int[] arr = {-8,-3,-1,5,7,9};
System.out.println(bin(arr,5));
}
public static int bin(int[] arr,int num){
int s = 0;
int e = arr.length-1;
while(s<=e){
int mid = (s+e)/2;
if(num==arr[mid]){
return mid;
}else if(num > arr[mid]){
s = mid+1;
}else{
e = mid-1;
}
}
return -1;
}
}
Recursive
=======
Code:
import java.util.*;
import java.lang.*;
import java.io.*;
class Codechef{
public static void main(String[] args){
int[] arr = {-8,-3,-1,5,7,9};
System.out.println(rec(5,arr,0,arr.length-1));
}
public static int rec(int val,int[] arr,int s,int e){
if(s<=e){
int mid = (s+e)/2;
int cmp = arr[mid];
if(cmp == val){
return mid;
}else if(cmp > val){
return rec(val,arr,s,mid-1);
}else{
return rec(val,arr,mid+1,e);
}
}
return -1;
}
}
Comments
Post a Comment