Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.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
Swift 速记_Swift - Fatal编程技术网

Swift 速记

Swift 速记,swift,Swift,所以我现在正在苹果网站上学习“快速旅行”教程。() 我在分类/速记部分感到困惑。给出的例子是 sort([1, 5, 3, 12, 2]) { $0 > $1 } 我打印了收尾,看看发生了什么,下面是我得到的: The $0 is 5 and the $1 is 1 The $0 is 3 and the $1 is 5 The $0 is 3 and the $1 is 1 The $0 is 12 and the $1 is 5 The $0 is 2 and the $1 is 1

所以我现在正在苹果网站上学习“快速旅行”教程。()

我在分类/速记部分感到困惑。给出的例子是

sort([1, 5, 3, 12, 2]) { $0 > $1 }
我打印了收尾,看看发生了什么,下面是我得到的:

The $0 is 5 and the $1 is 1
The $0 is 3 and the $1 is 5
The $0 is 3 and the $1 is 1
The $0 is 12 and the $1 is 5
The $0 is 2 and the $1 is 12
The $0 is 2 and the $1 is 5
The $0 is 2 and the $1 is 3
The $0 is 2 and the $1 is 1

在第一行,请注意$1是1,而$0是5。我的问题是,既然数字“1”位于数组的第一位,为什么不将其指定为$0(而不是$1)。我理解算法和所有…困扰我的只是简写属性。我猜是尼克皮基,但如果有人能帮我澄清这一点,我将不胜感激

这与速记无关,只是对排序的内部实现进行了优化。将参数传递给闭包的顺序无关紧要,因此在内部,它们将以任何碰巧有效的顺序传递

从比较的顺序来看,现在发生的似乎是插入排序——这是小型数据集的一种常见算法,快速排序通常选择在特定列表长度以上

正如您在最后处理2时所看到的,插入排序会对每个新元素进行排序,并遍历排序后的数据以找到其正确位置。因此,首先选择$0,然后依次为每个现有元素设置$1

在算法的一开始,没有进行比较,因此1永远不会放入$0槽中。所需的第一个比较是新元素5,即现有元素1