Sobes.tech
Junior

What is the complexity of searching for an element in a Swift array?

sobes.tech AI

Answer from AI

In the worst case (element not found or at the end), linear search is O(n), where n is the number of elements in the array.

Using binary search on a sorted array is logarithmic, O(log n).

// Linear search
let array = [1, 5, 2, 8, 3]
if array.contains(8) {
    // Element found. In the worst case, all elements were checked.
}

// Binary search on a sorted array
let sortedArray = [1, 2, 3, 5, 8]
// Implementation requires additional steps or using an algorithm
// For example, using the binarySearch() method for sorted collections in Swift 5.3+
// sortedArray.binarySearch(8)