我想提高我使用Swift排序算法的知识。选择排序算法的执行不起作用
交换功能自己正常工作,但是当我想在selectionSort函数中使用它时,它并没有达到我期望的效果。 myArray
未分类。
这里是我的代码:
func swap(var myArray:[Int], firstIndex: Int, secondIndex: Int) -> [Int] {
let temp = myArray[firstIndex]
myArray[firstIndex] = myArray[secondIndex]
myArray[secondIndex] = temp
return myArray
}
func indexOfMinimum(myArray:[Int], startIndex: Int) -> Int {
// Set initial values for minValue and minIndex,
// based on the leftmost entry in the subarray:
var minValue = myArray[startIndex]
var minIndex = startIndex
// Loop over items starting with startIndex,
// updating minValue and minIndex as needed:
for(var i = minIndex + 1; i < myArray.count; i++){
if(myArray[i] < minValue ) {
minIndex = i
minValue = myArray[i]
}
}
return minIndex
}
// This function is not working properly
func selectionSort(myArray: [Int]) {
var x: Int
for (var i = 0; i < myArray.count; i++) {
x = indexOfMinimum(myArray,startIndex: i)
swap(myArray, firstIndex: i, secondIndex: x)
}
}
var myArray2 = [22, 11, 99, 88, 9, 7, 42]
selectionSort(myArray2)
myArray2 // that is the result that I'm getting [22, 11, 99, 88, 9, 7, 42]
//while I should get [7, 9, 11, 22, 42, 88, 99]
您能更具体地了解什么“不起作用”? – Arc676
称为'selectionSort'的第三个函数不起作用。它对阵列没有任何作用。我试图让它返回一个整数数组的返回函数,但它不起作用 – AziCode
Swift数组是*值类型*,这意味着您的原始数组永远不会被修改。阅读有关inout参数... –