Apr 25, 2024 iOS

Find the largest three elements in an array using swift

Swift Program to find the largest of three number in given array

import Foundation


var array = [54,-3,23,45,5,32]

func getLargestofThreeNumbers(_ arr:[Int]) ->[Int]{
        var first = 0
        var second = 0
        var thrid = 0
        var large = [Int]()
        if arr.count < 3 {
            print("Invalid Input")
            return large
        }
        
        for i in 0 ..< arr.count {
            if arr[i] > first{
                thrid = second
                second = first
                first = arr[i]
               
            }
            else if(arr[i] > second){
                thrid = second
                second = arr[i]
               
                
            }
            else if (arr[i] > thrid){
                thrid = arr[i]
           
            }
        }
        large.append( first)
        large.append( second)
        large.append( thrid)
        return large
    }

    print(getLargestofThreeNumbers(array))

Leave a Reply

Your email address will not be published. Required fields are marked *