Monday, 9 January 2017

Implement Binary Search over an array of integers. A stub file has been given to you. The class Binary accepts an array of integers as input and a key to search and the binarySearch method returns the position of the number in the array. Note that if the number is found at the first position in the array, it should return 1 (and not 0). If the number is not found return -1. You can assume that the array supplied to the constructor is already sorted.

import java.util.*;
import java.lang.*;
import java.io.*;

class Binary
{
int []l;
int key;    
  public Binary(int[] l, int key) {
    this.l = l;
    this.key = key;
  }
  public int binarySearch() {
     
    int lb=0;
    int ub=l.length-1;
    if(key==l[0])
        return 1;
    while(lb<=ub)
             {
                int mid=((lb+ub)/2);
                if(key==l[mid])
                  return (mid+1);
                   
                    if(key<l[mid])
                     ub=mid-1;
                    else
                      lb=mid+1;
              }
                return -1;
             }
  }
 
class myclass {
    public static void main(String []args) {
        int a[]={1,2,3,4,5};
        int key=3;
        Binary b=new Binary(a,key);
        System.out.println(key+" is present at position "+(b.binarySearch()+1));
    }
}

No comments:

Post a Comment