Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

AIM: Program To Implement Binary Search Program

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

AIM: Program to implement Binary Search

Program:
import java.lang.reflect.Array;
import java.util.ArrayList;

public class BinarySearch {

public static <T extends Comparable<T>> int binarySearch(ArrayList<T> a, ArrayList<T>


b, int lo, int hi) {
if (lo < hi) {
int mid = (lo / 2) + (hi / 2);
int cmp = (a.get(mid)).compareTo(b.get(0));
if (cmp > 0) return binarySearch(a, b, lo, mid - 1);
if (cmp < 0) return binarySearch(a, b, mid + 1, hi);
return mid;
}
return -1;
}
public static void main(String[] args) {
ArrayList<Integer> a = new ArrayList<Integer>();
int value=6;
ArrayList<Integer> b = new ArrayList<Integer>();
a.add(1);
a.add(2);
a.add(3);
a.add(4);
a.add(6);
a.add(8);
a.add(9);
b.add(8);
value=BinarySearch.binarySearch(a,b,0,a.size()-1);
System.out.println("value is at:"+value);
}
}
OUTPUT:

You might also like