在ruby中按字母顺序比较字符串出错

时间:2014-01-23 00:19:11

标签: ruby search

我正在开发一种搜索字符串数组的二进制搜索算法,但是,在我的搜索中,“Canacee”的某些点被评估为比“administrate”字母顺序更低。有人知道为什么会这样吗? 我的代码:

class Array
def binary_search(val, low=0, high=(length - 1))
    return false if high < low
    mid = (low + high) / 2
    midvalue = self[mid].downcase.strip

    value = self[mid] <=> val
    printf "%s \t %s \t %d \t %d\n", midvalue, val, mid, value
    case
    when value==0 then return true
    when value > 0 then binary_search(val, low, mid-1)
    when value < 0 then binary_search(val, mid+1, high)
    end
  end
end

path = ARGV.length > 0 ? ARGV[0] : '/words'
entries = File.read(path).split("\n")

if entries.binary_search("administrate")
  printf "yes"
else
 printf "no"
end

但是,我无法在word文件中找到“administrate”这个词。 这是我得到的输出:

mogitocia    administrate    117467      1 
dysoxidation     administrate    58733   1 
canacee      administrate    29366   -1 
counterdistinction   administrate    44049   1 
citification     administrate    36707   1
cetomorphic      administrate    33036   1
castellanship    administrate    31201   1
carboxylase      administrate    30283   1
capelet      administrate    29824   1
cankery      administrate    29595   1
candied      administrate    29480   1
cancelation      administrate    29423   1
canalling    administrate    29394   1
canalage     administrate    29380   1
canadine     administrate    29373   1
canadian     administrate    29369   -1
canadianization      administrate    29371   -1
canadianize      administrate    29372   -1

1 个答案:

答案 0 :(得分:2)

更改

value = self[mid] <=> val

value = midvalue <=> val

否则您使用的是未展示self[mid]'C' 'a' {{1}} {{1}}之前{{1}}。{/}