Author: [Your Name]
Date: [Date]
1. Problem Description
This is the problem of finding the minimum value in a given integer array.
The array may contain duplicate values, and its length can be between 1 and 100,000.
The function should return the minimum value. If the array is empty, it should return nil.
Function Signature:
func findMinimum(in array: [Int]) -> Int?
2. Sample Input
- Input: [3, 5, 1, 2, 4] ➞ Output: 1
- Input: [10, 20, 30, 5, 15] ➞ Output: 5
- Input: [] ➞ Output: nil
- Input: [5, 5, 5, 5] ➞ Output: 5
3. Problem Solving Process
To solve this problem, a basic array searching algorithm can be used.
To find the minimum value, we need to traverse each element of the array and check if there is an element smaller than the current minimum.
Below is the process to solve the problem.
3.1. Algorithm Design
1. Check if the array is empty. If it is, return nil.
2. Initialize the first element as the minimum value.
3. Traverse each element of the array to find an element smaller than the current minimum.
4. If the minimum value is updated, continue to store it.
5. Return the final minimum value.
3.2. Time Complexity
This algorithm finds the minimum value in a single traversal of the array, so
the time complexity is O(n). Here, n is the length of the array.
Even in the worst-case scenario, we need to check all elements of the array, making it
an efficient approach.
3.3. Code Implementation
Now, let’s implement the above algorithm in Swift.
func findMinimum(in array: [Int]) -> Int? {
// If the array is empty
guard !array.isEmpty else {
return nil
}
var minimum = array[0] // Initialize with the first element
for number in array {
if number < minimum { // If it is less than the current minimum
minimum = number // Update the minimum
}
}
return minimum // Return the minimum
}
4. Test Cases
After writing the function, it is essential to test it with various inputs.
Below is the test code for several cases.
let testCases = [
([3, 5, 1, 2, 4], 1),
([10, 20, 30, 5, 15], 5),
([], nil),
([5, 5, 5, 5], 5),
([100, 200, 50, 150], 50)
]
for (input, expected) in testCases {
let output = findMinimum(in: input)
print("Input: \(input), Expected: \(expected), Output: \(String(describing: output))")
}
5. Conclusion
In this lesson, we implemented an algorithm to find the minimum value in a given array
using Swift. If you have understood the basic concepts and implementation methods of the algorithm,
it is also important to validate the logic through test cases with various inputs.
Work on more algorithmic problems in the future to improve your Swift coding skills!