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,31 @@
import Foundation
// Note: If you arent familiar with Comparable, please check out Generics chapter in Swift book
func binarySearch <T: Comparable>(_ list: [T], item: T) -> Int? {
// low and high keep track of which part of the list you'll search in.
var low = 0
var high = list.count - 1
// While you haven't narrowed it down to one element ...
while low <= high {
//... check the middle element
let mid = low + (high - low) / 2
let guess = list[mid]
// Found the item.
if guess == item {
return mid
}
// The guess was too high.
if guess > item {
high = mid - 1
} else {
low = mid + 1
}
}
return nil
}
let myList = [1, 3, 5, 7, 9]
print(binarySearch(myList, item: 3) ?? "Not Found") // => 1
print(binarySearch(myList, item: -1) ?? "Not Found") // => Not Found