Implement Binary Search in Swift

Algorithms Computer Science Binary Search Swift

14 Sep 2020 . 2 min read       @gurjitpt


In computer science, there are two types of algorithms commonly used to solve a problem searching and sorting algorithms. Its valuable to know which algorithm to use to perform a computation.In this tutorial, we will focus on searching algorithms.

When we talk about searching algorithms the use of binary search algorithm is very common. It is a very simple algorithm used to find a value within a sorted array.

How binary search algorithm works?

In binary search, we find specific value in sorted array by comparing that value to mid element of array. If value matches the mid element of array it returns the position from array. If value is less than mid element of array, then we search the left half of array. If value is greater than mid element of array, then we search the right half of array. We repeat this process until we either find a target or if subarray size is 0 then value is not in array.

Implement binary search in Swift

Now we will implement binary search step by step.

1. First of all, choose sorted array to search for

var arrayToSearch = [2,5,8,9,10,12,16]

2. Now choose target value to search in sorted array

var valueToFind = 10

3. Set low index and highIndex

var lowIndex = 0

var highIndex = arrayToSearch.count - 1

4. Create a function for performing binary search with two parameters, array of type [Int] and key of type Int. The function has return type Int? an optional type

func binarySearch(array:[Int], key: Int) -> Int? {

}

5. Now we will iterate over array using while loop. It will iterate until lowIndex is lower or equal than highIndex

while lowIndex <= highIndex {

}

6. Set position of middle element of array

let mid = (lowIndex + highIndex) / 2

7. If mid element of array matches target key than return mid element position

if array[mid] == key {
    return mid
}

8. If mid element of array less than target key than set lowIndex to mid + 1

else if array[mid] < key {
  lowIndex = mid + 1
}

9. If mid element of array greater than target key than set highIndex to mid - 1

else {
  highIndex = mid - 1
}

10. If target key doesn't matches any element from array it will return nil

return nil

Finally, perform binary search operation by calling binarySearch function. If target value found display message that value found at that position or otherwise if it returns nil display value not found.

var result = binarySearch(array: arrayToSearch, key: valueToFind)
if (result != nil) {
    print("Value found at \(result ?? 0)")
} else {
    print("Value not found")
}

Final code


import UIKit

var arrayToSearch = [2,5,8,9,10,12,15]
var valueToFind = 10
var lowIndex = 0
var highIndex = arrayToSearch.count - 1

func binarySearch(array:[Int], key: Int) -> Int? {
    while lowIndex <= highIndex {
        let mid = (lowIndex + highIndex) / 2
        if array[mid] == key {
            //print("Value found")
            return mid
        } else if array[mid] < key {
            lowIndex = mid + 1
        } else {
            highIndex = mid - 1
        }
    }
    return nil
}

var result = binarySearch(array: arrayToSearch, key: valueToFind)
if (result != nil) {
    print("Value found at \(result ?? 0)")
} else {
    print("Value not found")
}

Conclusion

It is very important to know which algorithm to be use to solve a problems or to perform a computation.Binary search algorithm is faster than another searching algorithms when array is larger in size. Binary search only can be apply when array is sorted.

Thanks!


Next Posts

The ultimate guide to iOS Unit Testing with Swift and Xcode

Unit testing is a testing method where you can test “unit” of code whether it is working as you want or not. In Xcode, use XCTest framework to perform unit tests.

Jun 29, 2020 . 2 min read     Xcode Testing

Read More »

Protocol Extensions in Swift Empty space for void

A protocol can defines a set of methods that can be adopted by any class, but we can’t write code inside.On the other hand, extensions gives us the power to write code inside methods..

May 01, 2020 . 1 min read     Swift

Read More »

Difference between Struct and Classes explained in Swift

Structures and Classes are basic templates for any application which consists of properties and methods implements for behaviour .You can define structure or class..

May 06, 2020 . 2 min read     Swift

Read More »