public class BinarySearchRecursion {
static int[] elements = {1,4,6,7,9,10,15,20,56,79,90,100};
static int index=-1;
public static void main(String[] args) {
int index=binarySearch(elements, 0, elements.length-1, 900);
if(index==-1){
System.out.println("element is not available in list");
}else{
System.out.println("element is available in list at position "+ index);
}
}
static int binarySearch(int[] A, int start, int end, int element){
int mid=(start+end)/2;
if(end<start){
return index+1;
}
if(A[mid]==element){
index=mid;
}else if (A[mid]>element) {
binarySearch(A, start, ((start+end)/2)-1, element);
}else {
binarySearch(A, ((start+end)/2)+1,end, element);
}
return index;
}
}
static int[] elements = {1,4,6,7,9,10,15,20,56,79,90,100};
static int index=-1;
public static void main(String[] args) {
int index=binarySearch(elements, 0, elements.length-1, 900);
if(index==-1){
System.out.println("element is not available in list");
}else{
System.out.println("element is available in list at position "+ index);
}
}
static int binarySearch(int[] A, int start, int end, int element){
int mid=(start+end)/2;
if(end<start){
return index+1;
}
if(A[mid]==element){
index=mid;
}else if (A[mid]>element) {
binarySearch(A, start, ((start+end)/2)-1, element);
}else {
binarySearch(A, ((start+end)/2)+1,end, element);
}
return index;
}
}
No comments:
Post a Comment