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

@@ -8,7 +8,7 @@ func binarySearch <T: Comparable>(_ list: [T], item: T) -> Int? {
// While you haven't narrowed it down to one element ... // While you haven't narrowed it down to one element ...
while low <= high { while low <= high {
//... check the middle element //... check the middle element
let mid = low + (high - low) / 2 let mid = (low + high) / 2
let guess = list[mid] let guess = list[mid]
// Found the item. // Found the item.
if guess == item { if guess == item {

View File

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