Why collection algorithms matter in Swift - Performance Analysis
When working with collections like arrays or lists, the way we search, sort, or filter them affects how fast our program runs.
We want to know how the time needed changes as the collection gets bigger.
Analyze the time complexity of the following code snippet.
let numbers = [1, 3, 5, 7, 9]
func containsNumber(_ target: Int, in array: [Int]) -> Bool {
for number in array {
if number == target {
return true
}
}
return false
}
let result = containsNumber(5, in: numbers)
This code checks if a number exists in an array by looking at each item one by one.
- Primary operation: Looping through the array elements one by one.
- How many times: Up to once for each item until the target is found or the end is reached.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
| 1000 | Up to 1000 checks |
Pattern observation: The number of checks grows directly with the size of the array.
Time Complexity: O(n)
This means the time to find a number grows in a straight line as the list gets bigger.
[X] Wrong: "Searching an unsorted list is always fast because computers are quick."
[OK] Correct: Even fast computers need to check each item one by one if the list is unsorted, so bigger lists take more time.
Understanding how collection algorithms grow with input size helps you explain your choices clearly and shows you know how to write efficient code.
"What if the array was sorted and we used a method that splits the search area in half each time? How would the time complexity change?"