Skip to content
This repository has been archived by the owner on Jul 10, 2024. It is now read-only.

Smallest 2 elements in an array in Swift #5740

Merged
merged 1 commit into from
Jun 28, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import Foundation

func findSmallestTwoElements(in array: [Int]) -> (Int, Int)? {
guard array.count >= 2 else {
print("Array should have at least two elements.")
return nil
}

var smallest = Int.max
var secondSmallest = Int.max

for number in array {
if number < smallest {
secondSmallest = smallest
smallest = number
} else if number < secondSmallest {
secondSmallest = number
}
}

return (smallest, secondSmallest)
}

// Example usage:
if let result = findSmallestTwoElements(in: [5, 3, 1, 2, 4]) {
print("The smallest element is \(result.0) and the second smallest element is \(result.1)")
} else {
print("Unable to find the smallest two elements.")
}