I have 2 functions, one that swaps the values of 2 elements in an array and another that is capable of finding the index of the smallest number in an array slice, now when I use then both to find the sorted array , I am unable to do so as I am not able to understand as to how to use the swap function
The Swap function
func swapData(arr: [Int], firstIndex: Int, secondIndex: Int) -> [Int] {
var temp = arr
var a = firstIndex
var b = secondIndex
var x = temp[a]
temp[a] = temp[b]
temp[b] = x
return temp
}
The function to find minIndex
func indexOfMinimum(arr:[Int], startIndex: Int) -> Int {
var newArray = arr[startIndex...]
var minValue = arr[newArray.startIndex]
var minIndex = 0
for i in newArray.startIndex 1 ..< newArray.endIndex {
if newArray[i] < minValue {
minValue = newArray[i]
minIndex = i - startIndex
}
}
return minIndex
}
The function that attempts to sort array using above 2
func selectionSort(arr: [Int]) {
var temp = arr
var minIndex = 0
for i in temp.startIndex ..< temp.endIndex {
minIndex = indexOfMinimum(arr: Array(temp[i..<temp.count]), startIndex: temp.startIndex)
swapData(arr: Array(temp[i..<temp.count]), firstIndex: temp.startIndex
, secondIndex: minIndex)
}
}
var demoList = [18, 6, 1,66, 44, 78, 9, 22, 1,23]
selectionSort(arr: demoList)
I keep getting the original unsorted array
CodePudding user response:
Without getting into whether or not your sort function works, it has a bigger problem. It is neither mutating the input array or returning a new one. Consider the following code:
func f(a: [Int]) {
// do stuff with `a`
}
var l = [1,2,3]
f(a: l)
// `l` is unchanged
Arrays in Swift are pass-by-value types. In order to change an array inside a function, you must return a new array or mark the array argument as inout and excplicitly pass a reference to it:
func f(a: inout [Int]) {
// do stuff with `a`
}
var l = [1,2,3]
f(a: &l)
// `l` may be changed