Tuesday, January 27, 2015

Closest Number Below (Binary Search)

Question: 
Given: array/list/whatever arr of integers, sorted (“people’s guesses”) target integer x (“actual price”)
Find the largest arr[i] <= x.

Idea: Binary Search.

Time: O(lgn) Space: O(1)

Code:
 public class ClosestNumber {  
      public ClosestNumber()  
      {  
           int[] input1={1};  
           int target1=6;  
           int[] input2={1,4};  
           int target2=2;  
           int[] input3={1,4,12};  
           int target3=8;  
           int[] input4={1, 13, 101,Integer.MAX_VALUE};  
           int target4=100;  
           System.out.println(binarySearch(input1,target1));  
           System.out.println(binarySearch(input2,target2));  
           System.out.println(binarySearch(input3,target3));  
           System.out.println(binarySearch(input4,target4));       
      }  
      //assume A!=empty  
      public int binarySearch(int[] A, int target)  
      {  
           int left=0;  
           int right=A.length-1;  
           while(left<=right)  
           {  
                int mid=(left+right)/2;  
                if(A[mid]==target)  
                     return target;  
                if(A[mid]<target)  
                     left=mid+1;  
                else  
                     right=mid-1;  
           }  
           return A[right];  
      }  
 }  

No comments:

Post a Comment