Last active
December 29, 2016 20:53
-
-
Save durul/ce65c3684417ad0f698ac9eedb4ff4d2 to your computer and use it in GitHub Desktop.
BinarySearch & LinearSearch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
import XCPlayground | |
import Foundation | |
func makeArr(n: Int) -> [Int] { | |
var res = [Int]() | |
for _ in 0..<n { | |
res.append(Int(arc4random_uniform(10000) + 1)) | |
} | |
return res | |
} | |
var arr = makeArr(n: 32) | |
arr.sort() | |
// Linear Search | |
var linearSearchSteps = 0 | |
func linearSearch(_ array: [Int], key: Int) -> Int? { | |
for (index, element) in array.enumerated() { | |
linearSearchSteps = linearSearchSteps + 1 | |
if element == key { | |
return index | |
} | |
} | |
return nil | |
} | |
// Binary Search | |
var binarysearchSteps = 0 | |
func binarySearch<T: Comparable>(_ array: [T], key: T, range: Range<Int>) -> Int? { | |
if range.lowerBound >= range.upperBound { | |
// search key is not in the array | |
return nil | |
} else { | |
// split array at midpoint | |
let midIndex = range.lowerBound + (range.upperBound - range.lowerBound) / 2 | |
binarysearchSteps = binarysearchSteps + 1 | |
// Check left half? | |
if array[midIndex] > key { | |
return binarySearch(array, key: key, range: range.lowerBound ..< midIndex) | |
} else if array[midIndex] < key { // Check Right half? | |
return binarySearch(array, key: key, range: midIndex + 1 ..< range.upperBound) | |
} else { // We have found the item | |
return midIndex | |
} | |
} | |
} | |
// Pick out a random index | |
let randomIndex = Int(arc4random_uniform(UInt32(arr.count) - 1)) | |
let randomNo = arr[randomIndex] | |
// Perform linear search | |
let linearFoundIndex = linearSearch(arr, key: randomNo) | |
// Perform binary search | |
let binaryFoundIndex = binarySearch(arr, key: randomNo, range: 0 ..< arr.count) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment