Sobes.tech
Junior — Middle

What methods can be used for quick element search in a sorted array, minimizing time costs?

sobes.tech AI

Answer from AI

For quick search in a sorted array, binary search algorithm is usually used. It minimizes time costs by working in O(log n) time, where n is the size of the array.

Idea of binary search:

  • Compare the target element with the middle element of the array.
  • If they are equal, the element is found.
  • If the target is less, repeat the search in the left half.
  • If greater, in the right half.

In iOS (Swift), you can use the binarySearch method or implement it yourself.

Example in Swift:

func binarySearch<T: Comparable>(_ array: [T], target: T) -> Int? {
    var low = 0
    var high = array.count - 1
    while low <= high {
        let mid = (low + high) / 2
        if array[mid] == target {
            return mid
        } else if array[mid] < target {
            low = mid + 1
        } else {
            high = mid - 1
        }
    }
    return nil
}

let sortedArray = [1, 3, 5, 7, 9]
if let index = binarySearch(sortedArray, target: 5) {
    print("Element found at position \(index)")
} else {
    print("Element not found")
}
What methods can be used for quick element search in… - sobes.tech