From 3d72ed841c1f704034694fd9033f3b218e9ad2e6 Mon Sep 17 00:00:00 2001 From: Riyazul555 Date: Sun, 16 Jun 2024 18:18:04 +0530 Subject: [PATCH] Smallest 2 elements in an array in Swift --- .../FindTheSmallestTwoElementsInAnArray.swift | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 program/program/find-the-smallest-two-elements-in-an-array/FindTheSmallestTwoElementsInAnArray.swift diff --git a/program/program/find-the-smallest-two-elements-in-an-array/FindTheSmallestTwoElementsInAnArray.swift b/program/program/find-the-smallest-two-elements-in-an-array/FindTheSmallestTwoElementsInAnArray.swift new file mode 100644 index 000000000..6eaa35e9c --- /dev/null +++ b/program/program/find-the-smallest-two-elements-in-an-array/FindTheSmallestTwoElementsInAnArray.swift @@ -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.") +}