// A function that finds the two largest elements in any collection of Comparable types.
// Returns a labeled tuple containing (largest, secondLargest), or nil if fewer than 2 elements exist.
func findTwoLargest<T: Comparable>(_ collection: [T]) -> (largest: T, secondLargest: T)? {
// Guard clause to ensure safety for collections with fewer than 2 elements
guard collection.count >= 2 else {
return nil
}
// Initialize largest and second largest based on the first two elements
var largest: T
var secondLargest: T
if collection[0] > collection[1] {
largest = collection[0]
secondLargest = collection[1]
} else {
largest = collection[1]
secondLargest = collection[0]
}
// Iterate through the remainder of the collection in a single O(N) pass
for index in 2..<collection.count {
let item = collection[index]
if item > largest {
// New absolute maximum found; old max shifts down to second largest
secondLargest = largest
largest = item
} else if item > secondLargest {
// Greater than second largest, but not the absolute maximum
secondLargest = item
}
}
return (largest, secondLargest)
}
// MARK: - Program Execution
// Define the dataset using a Swift array
let data = [3, 4, 9, 6, 7, 1, 2, 5]
// Call our function and handle the optional tuple result idiomatically
if let result = findTwoLargest(data) {
print("Dataset: \(data)")
print("The largest element is: \(result.largest)")
print("The second largest element is: \(result.secondLargest)")
} else {
print("Error: The collection must contain at least two elements.")
}
/*
run:
Dataset: [3, 4, 9, 6, 7, 1, 2, 5]
The largest element is: 9
The second largest element is: 7
*/