合并排序实施

时间:2012-05-21 19:29:35

标签: sorting

我无法获得正确的排序列表。我不确定我做错了什么。

merge_sort = function(list)
{
    #split list in half
    #sort each half
    #merge each half
    if(length(list<2))
        result = list
    else
    {
        middle = ceiling(length(list)/2)
        left = list[1:middle]
        right = list[middle+1:length(list)]
        merge_sort(left)
        merge_sort(right)
        while(min(length(left),length(right)) >0)
        {
            if(left[1] < right[1])
            {
                result = c(result,left[1])
                if(min(length(left),length(right)) >= 2)
                { 
                result = c(result,left[2:length(left)])
                result = c(result, right[2:length(right)])
                }
            }               
            else
            {
                result = c(result,right[1])
                if(min(length(left),length(right)) >= 2)
                { 
                result = c(result,right[2:length(right)])
                result = c(result, left[2:length(left)])
                }
            }
        }

    }
    return(result)
    print(result)
}

1 个答案:

答案 0 :(得分:0)

是否应该使用right = list[middle:length(list)]代替right = list[middle+1:length(list)]