How to find the two largest elements in an array with Swift

2 Answers

0 votes
func twoLargest(_ arr: [Int]) 	{
    let size: Int = arr.count;
			
	var max: Int = Int.min;
	var secondmax: Int = Int.min;
	
	for i in 1...size - 1 {
	    if (arr[i] > max) {
            secondmax = max;
            max = arr[i]; 
        } else if (arr[i] < max && arr[i] > secondmax) {
                    secondmax = arr[i]; 
                }
	}

	print("First Largest:", max);
	print("Second Largest:", secondmax);
}


let arr: [Int] = [7, 3, 0, 8, 2, 5, 99, 4, 6];
		
twoLargest(arr);




/*
run:

First Largest: 99
Second Largest: 8

*/

 



answered Dec 18, 2021 by avibootz
0 votes
// 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
 
*/

 



answered 18 hours ago by avibootz
...