Junior — Middle
Describe an example algorithm used for searching an element in a data structure.
sobes.tech AI
Answer from AI
One of the basic algorithms for searching for an element in a data structure is binary search, which is applied to sorted arrays. It works on the principle of dividing the array in half and comparing the desired value with the middle element.
Example in Swift:
func binarySearch(_ array: [Int], target: Int) -> Int? {
var left = 0
var right = array.count - 1
while left <= right {
let mid = (left + right) / 2
if array[mid] == target {
return mid
} else if array[mid] < target {
left = mid + 1
} else {
right = mid - 1
}
}
return nil
}
let numbers = [1, 3, 5, 7, 9, 11]
if let index = binarySearch(numbers, target: 7) {
print("Element found at position \(index)")
} else {
print("Element not found")
}