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