4

我是 Ruby 新手,我正在尝试Wikipedia 中给出的合并排序算法

在合并方法中比较左右数组的第一个元素时,我收到“Fixnum 与数组的比较失败(ArgumentError)”失败错误。可能是什么原因,我该如何解决这个问题?谢谢 :)

def mergeSort(array)
    if array.length == 1
        return array
    end

    middle = array.length/2 - 1
    left = array[0..middle]
    right = array[middle+1..array.length-1]

    left = mergeSort(left)
    right = mergeSort(right)
    merge(left,right)
end


def merge(left,right)
    result = []
    while left.length > 0 || right.length > 0
        if left.length > 0 && right.length > 0
            one = left[0]
            two = right[0]
            puts ("one's class is #{one.class} two's class is #{two.class} two is #{two}")
            if one <= two
                result << left.shift
            else
                result << right.shift
            end
        elsif left.length > 0
            result.push(left)
            left = []
        else
            result.push(right)
            right = []
        end 
    end
    puts "result is #{result}"
    result
end
4

1 回答 1

5

错误在以下几行:

    elsif left.length > 0
        result.push(left)
        left = []
    else
        result.push(right)
        right = []
    end

一个简单的例子应该说明原因:

irb(main):067:0> a=[1,2]
=> [1, 2]
irb(main):068:0> b=[3,4]
=> [3, 4]
irb(main):069:0> a.push(b)
=> [1, 2, [3, 4]]

而不是push(),尝试concat()

于 2011-11-13T08:51:02.833 回答