Binary Search using Swift - iOS Coding Challenge

Let's Code



//: Playground - noun: a place where people can play

import UIKit
import Foundation

var array : [Int] = [1,4,2,3,5,6,76,32,43,12,55,88,99,49,76,78,90,11,99]
let key = 55

func binarySearch(array : [Int] , key : Int) -> Bool {
    let minIndex = 0
    let maxIndex = array.count - 1
    let midIndex = maxIndex / 2
    let midValue = array[midIndex]
    
    if(key < array[minIndex] || key > array[maxIndex]){
        return false
    }
    if key < midValue {
        let arraySlice = Array(array[0...midIndex - 1])
        return binarySearch(array: arraySlice, key: key)
    }
    if key > midValue {
        let arraySlice = Array(array[midIndex + 1...maxIndex])
        return binarySearch(array: arraySlice, key: key)
    }
    if key == midValue {
        return true
    }
    return false
}

print("Input Array is \(array)")
array = array.sorted()
print("Sorted Array is \(array)")
if binarySearch(array: array, key: key) {
    print("Key : \(key)")
    print("Found key")
}
else{
    print("Key : \(key)")
    print("Not Found")
}


Result






Comments

Popular posts from this blog

Best coding practice and structure for redux saga with react hooks | Separate watcher and worker saga | React clean code

How to use redux with React Hooks - Creating TodoList

Setting up Redux Devtools for React applications