Find the second largest number and its Index
Code
func findSecondLargest(arr: [Int]) -> (number: Int, index: Int)? {
var largest = Int.min
var secondLargest = Int.min
var largestIndex = -1
var secondLargestIndex = -1
for (index, num) in arr.enumerated() {
if num > largest {
secondLargest = largest
secondLargestIndex = largestIndex
largest = num
largestIndex = index
} else if num > secondLargest && num != largest {
secondLargest = num
secondLargestIndex = index
}
}
// If a second largest number was found, return it along with its index
if secondLargestIndex != -1 {
return (number: secondLargest, index: secondLargestIndex)
} else {
return nil // No second largest number found
}
}
Example
// Example usage
let array = [5, 2, 18, 3, 4, 7, 1, 6, 3]
if let result = findSecondLargest(arr: array) {
print("Second largest number: \(result.number)")
print("Index: \(result.index)")
} else {
print("No second largest number found.")
}
Output
Second largest number: 7
Index: 5