这是从下到上的一种。虽然循环迭代被替换为数组中的最小数字,但这一直持续到最后。
正如你所看到的,我正在重构以使用步幅。不幸的是var lowest = firstIndex
给了我一些麻烦。
我应该可以使用stride完成此功能吗?我相信我应该使用stride: to
代替stride: through
。感谢Tim的提示。
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
}
答案 0 :(得分:1)
我让它像这样工作:
func selOrganize(myList: Array<Int>) -> Array<Int> {
var extract = myList
// Accessing indices is simpler than calling enumerate, and
// the function only needs access to the indices, not the
// values of the enumeration:
for firstIndex in extract.indices {
// lowest needs to be defined inside this loop if you
// are going to initialize it using firstIndex
// because firstIndex isn't defined outside the loop.
var lowest = firstIndex
// You need to stride from the firstIndex to the end of the
// array, so the call to stride should look like this:
for secondIndex in firstIndex.stride(to: extract.count, by: 1) {
if extract[lowest] > extract[secondIndex] {
lowest = secondIndex
}
}
if firstIndex != lowest {
swap(&extract[firstIndex], &extract[lowest])
}
}
return extract
}
答案 1 :(得分:1)
Stride
,您可以使用标准for i in start..<end
语法
func selOrganize(myList: Array<Int>) -> Array<Int> {
var extract = myList
for firstIndex in 0..<extract.count {
var lowest = firstIndex
for secondIndex in (firstIndex + 1)..<extract.count {
if extract[lowest] > extract[secondIndex] {
lowest = secondIndex
}
}
if firstIndex != lowest {
swap(&extract[firstIndex], &extract[lowest])
}
}
return extract
}
但实际上你可以在一行中做同样的事情
let sortedList = myList.sort{$0 < $1}