合并两个排序的数组 - 为什么这不起作用?

时间:2014-06-15 20:07:15

标签: ruby algorithm merge array-merge

我正在学习ruby并获得以下任务:

given two sorted arrays like the following we must merge them into one sorted array.
array_1 = [5,8,9,11]
array_2 = [4,6,7,10]

merge(array_1, array_2)

=> [4,5,6,7,8,9,10,11]

Given this brief description, implement the merge method that takes two arrays and returns
 the properly sorted array containing the items from each array.

我写了这个答案:

def merge(arr1, arr2)
  i = 0
  k = 0
  merged_arr = []
  until k = arr2.count
    while arr1[i] <= arr2[k]
      merged_arr.push(arr1[i])
      i += 1
    end
    merged_arr.push(arr2[k])
    k += 1
 end
 merged_arr
end

我的导师发出了一个解决方案,我理解,但是我不明白为什么我的答案不起作用。有人可以解释错误的逻辑吗?谢谢!

这是(正确的)解决方案:

def merge(array_1, array_2)
    i = 0
    k = 0
    merged_array = []
    while i < array_1.count
        while k < array_2.count && array_1[i] > array_2[k]
            merged_array << array_2[k]                      
            k += 1                                          
        end
        merged_array << array_1[i]
        i += 1                                              
    end
    print merged_array.inspect
 end

2 个答案:

答案 0 :(得分:2)

k = arr2.countarr2.count的值分配给k并评估为k,因此永远不会执行until k = arr2.count

答案 1 :(得分:0)

你还需要考虑arr1和arr2的长度不等,你的教练解决方案只有在arr1.length&gt; = arr2.length时才是正确的,但如果是arr1.length&lt; arr2.length,然后解决方案中丢失了额外长度的元素。