Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,879 questions

51,805 answers

573 users

How to implement recursive binary search in Swift

1 Answer

0 votes
import Foundation

func recursiveBinarySearch(arr: [Int], left: Int, right: Int, toFind: Int) -> Int {
    if right >= left {
        let mid = left + (right - left) / 2

        if arr[mid] == toFind {
            return mid
        }

        if arr[mid] > toFind {
            return recursiveBinarySearch(arr: arr, left: left, right: mid - 1, toFind: toFind)
        }

        return recursiveBinarySearch(arr: arr, left: mid + 1, right: right, toFind: toFind)
    }

    return -1
}

let arr = [2, 3, 6, 7, 8, 12, 13, 17, 19, 21, 22, 28]
let toFind = 17

let index = recursiveBinarySearch(arr: arr, left: 0, right: arr.count - 1, toFind: toFind)

if index == -1 {
    print("not found")
} else {
    print("Found at index: \(index)")
}




/*
run:  
 
Found at index: 7
 
*/

 



answered Dec 13, 2024 by avibootz
...