Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,950 questions

51,892 answers

573 users

How to find the second largest element in an array with Swift

1 Answer

0 votes
func getTheSecondlargest(_ arr: [Int]) -> 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]; 
                }
	}

	return secondmax;
}


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




/*
run:

8

*/

 



answered Dec 18, 2021 by avibootz

Related questions

...