Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby上的排序程序_Ruby_Sorting - Fatal编程技术网

Ruby上的排序程序

Ruby上的排序程序,ruby,sorting,Ruby,Sorting,我在Ruby上看过以下排序程序,但我不认为我完全理解它的实际工作原理: def sort arr rec_sort arr, [] end def rec_sort unsorted, sorted if unsorted.length <= 0 return sorted end smallest = unsorted.pop still_unsorted = [] unsorted.each do |tested

我在Ruby上看过以下排序程序,但我不认为我完全理解它的实际工作原理:

def sort arr
    rec_sort arr, []  
end

def rec_sort unsorted, sorted

    if unsorted.length <= 0
        return sorted
    end
    smallest = unsorted.pop
    still_unsorted = []

    unsorted.each do |tested|
        if tested < smallest 
            still_unsorted.push smallest
            smallest = tested
        else 
            still_unsorted.push tested
        end
    end
    sorted.push smallest
    rec_sort still_unsorted, sorted
end

puts sort ["satoshi", "Bitcoin", "technology", "universe", "smell"]

=> Bitcoin
   satoshi
   smell
   technology
   universe
我知道each循环首先选择单词“Bitcoin”(因为排序时它确实会排在第一位),而“Bitcoin”将被放入数组“sorted”。我不太明白的是,为什么这里有几个“比特币”,因为在每个循环的第一次迭代中,它应该被排除在“未排序”数组之外,因此不能出现在接下来的迭代中,这使得“比特币”不可能多次出现在“排序”数组中

你能告诉我是什么让这两者如此不同吗?
如有任何建议,将不胜感激。谢谢。

仍然未排序的
数组删除了
最小的
元素,但是
未排序的
数组只删除了最后一个元素。

据我所知,它是的递归实现。对于您来说,除了语句
unsorted.pop
之外,混乱
unsorted
不会被修改,而只会被复制到
仍然未排序的
中,该数组中最小的元素除外

我正在[3,1,2]上为你做这个

unsorted = [3,1,2]
sm = unsorted.pop # sm = 2 unsorted = [3,1]
still_unsorted = []
#after loop unsorted.each
# still_unsorted = [2,3]
# unsorted = [3,1]
# sm = 1
# sorted = [1]

在接下来的2次迭代中,您将了解发生了什么

,据我所知,这是一个递归实现。对你来说,混乱
未排序
除了声明
未排序
之外没有被修改。pop
只是被复制到
仍然未排序
中,除了你知道的数组中最小的元素,放入[“satoshi”、“比特币”、“技术”、“宇宙”、“气味”]。排序给你什么都不需要?,您的示例中使用的排序算法看起来很笨拙,如果您对排序技术感兴趣,我将寻找其他来源
unsorted = [3,1,2]
sm = unsorted.pop # sm = 2 unsorted = [3,1]
still_unsorted = []
#after loop unsorted.each
# still_unsorted = [2,3]
# unsorted = [3,1]
# sm = 1
# sorted = [1]