这是一种从下到上的排序。循环时,迭代被数组中的最小数字替换,并且一直持续到最后。
如您所见,我正在重构以使用 stride。不幸var lowest = firstIndex
的是给我带来了一些麻烦。
我应该可以使用 stride 来完成这个功能,对吧?我相信我应该使用stride: to
而不是stride: through
. 感谢蒂姆的提示。
func selOrganize(myList: Array<Int>) -> Array<Int> { 1
var extract = myList
for firstIndex in 0..<extract.count {
var lowest = firstIndex
for var secondIndex = firstIndex + 1; secondIndex < extract.count; secondIndex++ {
if extract[lowest] > extract[secondIndex] {
lowest = secondIndex
}
}
if firstIndex != lowest {
swap(&extract[firstIndex], &extract[lowest])
}
}
return extract
}
更新的语法
func selOrganize(myList: Array<Int>) -> Array<Int> {
var extract = myList
// var lowest = firstIndex
// Do I need 'key'? Should I declare 'lowest' as a variable here?
// If I do use it here I get a "'lowest' is unmutable because it's a let" error
for (firstIndex, key) in extract.enumerate() {
// < > stride uses 'to' and <= >= stride uses through
for secondIndex in (firstIndex).stride(to: 0, by: +1) {
if extract[lowest] > extract[secondIndex] {
lowest = secondIndex
}
}
if firstIndex != lowest {
swap(&extract[firstIndex], &extract[lowest])
}
}
return extract
}