Ruby与Java对比算法实现-二分法查找

1 条评论 , 2 次修正,4982 次阅读,最后更新于 2012年04月21日
#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);
 }