ruby普通二分查找和递归二分查找

2017-12-18 18:35:56来源:CSDN作者:o83290102o5人点击

分享
#普通二分查找  def binSearch(arr,value)    left=0    right=arr.length-1    while left<=right      center=(left+right)/2      if arr[center]== value        return center      elsif arr[center]<value        left=center+1      else        right=center-1      end    end    return -1end#递归二分查找def binSearchRecursive(arr,value)  left=0  right=arr.length-1  _binSearchRecursive(arr,value,left,right)end#inner fundef _binSearchRecursive(arr,value,left,right)  center=(left+right)/2  if right-left<0    return -1  elsif arr[center]==value    return center  elsif arr[center]>value    return _binSearchRecursive(arr,value,left,center-1)  else arr[center]<value    return _binSearchRecursive(arr,value,center+1,right)  endendarr=[1,2,3,4,5,6,7]puts binSearch(arr,5)puts binSearchRecursive(arr,5)

欢迎关注我的github https://github.com/luckyCatMiao

最新文章

123

最新摄影

闪念基因

微信扫一扫

第七城市微信公众平台