评论
suxu 发表于
#Ruby 二分发查找
def self.binary_search
  a = [10,57,68,70,78,90,122]
  search = 78
  index = 0 , start_index = 0 , end_index = a.length
  while(true)
    index = start_index + ((end_index - start_index) / 2)
    start_index = index if a[index] < search
    end_index = index if a[index] > search
    break if a[index] == search
   end
   puts "find by " + index.to_s
end


//Java 二分发查找
public static void main(String[] args) {
        // sorted array
     int[] a = {10,57,68,70,78,90,122};
     int search = 78;
     int index = 0;
     int start = 0;
     int end = a.length;
    while(true){
        //get index
        index = start+((end-start)/2);
        if(a[index]<search){
            start = index;
        }else if(a[index]>search){
            end = index;
        }else{
            break;
        }
    }
     System.out.println("find by "+ index);
 }