Add examples on Swift 3.0.2 (#11)
* 01_binary_search Swift 3.0.2 * 01_binary_search Swift 3.0.2 * add Chapter 2 - 01_selection_sort Swift 3.0.2 example * 01_binary_search cosmetic note updates Swift 3.0.2 * 03_recursion Swift 3.0.2 examples * 04_quicksort Swift 3.0.2 examples * fix typo on quicksort example. Swift 3.0.2 * add 05_hash_tables examples on Swift 3.0.2 * add 01_breadth-first_search Swift 3.0.2 example * 01_breadth-first_search fixing typo Swift 3.0.2 * add 01_dijkstras_algorithm on Swift 3.0.2 * add 08_greedy_algorithms Swift 3.0.2 example * 01_longest_common_subsequence Swift 3.0.2 example
This commit is contained in:
committed by
Aditya Bhargava
parent
62ed616954
commit
12265a8c61
38
02_selection_sort/swift/01_selection_sort.swift
Normal file
38
02_selection_sort/swift/01_selection_sort.swift
Normal file
@@ -0,0 +1,38 @@
|
||||
import Foundation
|
||||
|
||||
// Finds the smallest value in an array
|
||||
func findSmallestIndex <T: Comparable> (_ arr: [T]) -> Int {
|
||||
// Stores the smallest value
|
||||
var smallest = arr[0]
|
||||
// We don't need any calculation if the array lenght 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 {
|
||||
if arr[i] < smallest {
|
||||
smallest = arr[i]
|
||||
smallestIndex = i
|
||||
}
|
||||
}
|
||||
return smallestIndex
|
||||
}
|
||||
|
||||
// Sort array
|
||||
func selectionSort <T: Comparable> (arr: [T]) -> [T] {
|
||||
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 {
|
||||
//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)
|
||||
}
|
||||
return newArr
|
||||
}
|
||||
|
||||
print(selectionSort(arr: [5, 3, 6, 2, 10])) // => [2, 3, 5, 6, 10]
|
||||
|
||||
|
||||
Reference in New Issue
Block a user