Junior — Middle
Can you name algorithms for searching elements in an array and briefly describe how they work?
sobes.tech AI
Answer from AI
Main algorithms for searching elements in an array:
-
Linear Search
- Goes through the array sequentially, comparing each element with the target.
- Works on any array, does not require sorting.
- In the worst case, complexity is O(n).
-
Binary Search
- Works only on sorted arrays.
- Divides the array in half, compares the middle element with the target, then searches in the left or right half.
- Complexity is O(log n).
Example of binary search 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
}