From 1f9061ff98e5a315360ded17735527bd44f3b571 Mon Sep 17 00:00:00 2001 From: Suparna Khamaru Date: Sun, 14 Jun 2020 23:05:51 +0530 Subject: [PATCH] Binary Search --- BinarySearch.swift | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 BinarySearch.swift diff --git a/BinarySearch.swift b/BinarySearch.swift new file mode 100644 index 0000000..807a2ba --- /dev/null +++ b/BinarySearch.swift @@ -0,0 +1,37 @@ +import UIKit + +/// The below function returns multiple result: 'found' Result & 'indexValue' of Result +/// when searched in an array using Binary Search + +func BinarySearch(valueToSearch: Int) -> (Bool, Int?) { + + let numbers = [1, 5, 15, 17, 19, 22, 24, 31, 105, 150] + + var left = 0 + var right = numbers.count - 1 + var middle = 0 + var found = false + var index: Int? + + while left <= right { + middle = (left + right) / 2 + + if numbers[middle] == valueToSearch { + found = true + index = middle + break + } + else if numbers[middle] < valueToSearch { + left = middle + 1 + } + else { + right = middle - 1 + } + } + return (found, index) +} + +print(BinarySearch(valueToSearch: 31)) // (true, Optional(7)) +print(BinarySearch(valueToSearch: 99)) // (false, nil) +print(BinarySearch(valueToSearch: 13)) // (false, nil) +print(BinarySearch(valueToSearch: 17)) // (true, Optional(3))