我想提高我使用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參數... –