Ruby实现二分法查找_Ruby_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > Ruby > Ruby实现二分法查找

Ruby实现二分法查找

 2013/1/25 11:09:47  suxu  程序员俱乐部  我要评论(0)
  • 摘要:defbinary_searcha=[10,57,68,70,78,90,122]search=78index=0,start_index=0,end_index=a.lengthwhile(true)index=start_index+((end_index-start_index)/2)start_index=indexifa[index]<searchend_index=indexifa[index]>
  • 标签:实现 查找 Ruby

?

def 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
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);
	 }
发表评论
用户名: 匿名