Few changes in Swift Code (#191)

* Replaced the confusing construction

* The algorithm works faster than the previous version
This commit is contained in:
Kostarev Kirill
2021-03-14 18:42:14 +03:00
committed by GitHub
parent c1c68d9d2a
commit fec65db129
2 changed files with 8 additions and 9 deletions

View File

@@ -4,13 +4,9 @@ import Foundation
func findSmallestIndex <T: Comparable> (_ arr: [T]) -> Int {
// Stores the smallest value
var smallest = arr[0]
// We don't need any calculation if the array length is 1
if arr.count == 1 {
return 0
}
// Stores the index of the smallest value
var smallestIndex = 0
for i in 1...arr.count-1 {
for i in 1..<arr.count {
if arr[i] < smallest {
smallest = arr[i]
smallestIndex = i
@@ -21,14 +17,17 @@ func findSmallestIndex <T: Comparable> (_ arr: [T]) -> Int {
// Sort array
func selectionSort <T: Comparable> (arr: [T]) -> [T] {
// We don't need any calculation if the array length is 1
guard arr.count > 1 else { return arr }
var newArr: [T] = []
// We have to make mutableArray reference copy of original array, because Swift 3 doesn't allow to get var parameter
var mutableArr = arr
for _ in 0...mutableArr.count-1 {
for _ in 0..<mutableArr.count {
//Finds the smallest element in the array and adds it to the new array
let smallestIndex = findSmallestIndex(mutableArr)
newArr.append(mutableArr[smallestIndex])
mutableArr.remove(at: smallestIndex)
newArr.append(mutableArr.remove(at: smallestIndex))
}
return newArr
}