Searching is one of the most common problems in computer science and coding interviews. In this post, we’ll learn about two basic searching techniques — Linear Search and Binary Search — and see how they work with simple Swift code examples.
🔎 What is Linear Search?
Linear Search is the simplest searching technique.
- Go through the array element by element.
- Compare each element with the target.
- If found → return the index.
- If not found → return
nil
.
Time complexity: O(n)
Linear Search in Swift
func linearSearch(_ array: [Int], target: Int) -> Int? {
for (index, value) in array.enumerated() {
if value == target {
return index
}
}
return nil
}
let numbers = [4, 8, 15, 16, 23, 42]
if let index = linearSearch(numbers, target: 23) {
print("Found at index \(index)") // Found at index 4
} else {
print("Not found")
}
🔎 What is Binary Search?
Binary Search is a faster searching algorithm but it only works on sorted arrays.
- Binary Search is a searching algorithm.
- It only works on sorted arrays.
- Instead of checking every element one by one (like linear search), it:
- Looks at the middle element.
- If the target is smaller → search the left half.
- If the target is larger → search the right half.
- Repeat until found or array is empty.
Time complexity: O(log n)
Binary Search in Swift
func binarySearch(_ array: [Int], target: Int) -> 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 sortedNumbers = [4, 8, 15, 16, 23, 42]
if let index = binarySearch(sortedNumbers, target: 23) {
print("Found at index \(index)") // Found at index 4
} else {
print("Not found")
}
Conclusion
- Use Linear Search when the array is small or unsorted.
- Use Binary Search when the array is large and sorted.
Both are fundamental algorithms often asked in technical interviews. Mastering them will also help you understand more advanced algorithms later.