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:
Anthony Marchenko
2017-03-16 02:05:38 +03:00
committed by Aditya Bhargava
parent 62ed616954
commit 12265a8c61
21 changed files with 467 additions and 0 deletions

View 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]