Step 1: Find minimum element in array & swap with beginning element
Step 2: So now swap min elements from inner loop in the array.
// TC: O(n^2)
// SC: O(1)
func selectionSort(_ arr: inout [Int]) {
for i in 0..<arr.count {
var minIndex = i
for j in i+1..<arr.count {
if arr[j] < arr[minIndex] {
minIndex = j
}
}
arr.swapAt(i, minIndex)
}
}
var arrayToSort: [Int] = [9,2,11,24,1,5]
selectionSort(&arrayToSort)
print("Sorted Array--> ", arrayToSort)// [1, 2, 5, 9, 11, 24]
So we have taken `minIndex` which assigned from 0th element i array till last & compare it with i+1 element