In: Computer Science
//Java program
import java.util.Random;
public class BinarySearch {
public static void bubbleSort(int a[],int n){
for(int i=n-1;i>=0;i--){
for(int
j=0;j<i;j++){
if(a[j]>a[j+1]){
int temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
}
public static int binarySearch(int a[], int key, int
low, int high)
{
if (high <= low)
return ((key > a[low])? (low + 1): low) +1;
int mid = (low + high)/2;
if(key == a[mid]) return mid;
if(key > a[mid]) return binarySearch(a, key, mid+1,
high);
return binarySearch(a, key, low, mid-1);
}
public static void main(String args[]) {
int arr[] = {1, 4, 13, 43, -25, 17,
22, -37, 29};
bubbleSort(arr,arr.length);
System.out.println("Index of 4 :
"+binarySearch(arr,4,0,arr.length-1));
System.out.println("Index of 100 :
"+binarySearch(arr,100,0,arr.length-1));
int arr1[] = {1, 4, 4, 22, -5, 10,
21, -47, 23};
bubbleSort(arr1,arr1.length);
System.out.println("\n\nIndex of 4
: "+binarySearch(arr1,4,0,arr1.length-1));
System.out.println("Index of 100 :
"+binarySearch(arr1,6,0,arr1.length-1));
int arr2[] = new int[20];
Random random = new Random();
for(int i=0;i<20;i++) {
arr2[i] =
-100+random.nextInt(200);
}
bubbleSort(arr2,arr2.length);
System.out.println("\n\nIndex of 10
: "+binarySearch(arr2,4,0,arr2.length-1));
}
}
//sample output