From 24fa08f19bf1e55d246d66b0f643f0ba8a36dd39 Mon Sep 17 00:00:00 2001 From: Md Riyazul Islam <121575277+Riyazul555@users.noreply.github.com> Date: Sun, 16 Jun 2024 22:40:59 +0530 Subject: [PATCH] Smallest 3 elements in an array in Swift (#5724) Co-authored-by: Riyazul555 Co-authored-by: Anandha Krishnan S Co-authored-by: Ritesh Kokam <61982298+RiteshK-611@users.noreply.github.com> --- ...indTheSmallestThreeElementsInAnArray.swift | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 program/program/find-the-smallest-three-elements-in-an-array/FindTheSmallestThreeElementsInAnArray.swift diff --git a/program/program/find-the-smallest-three-elements-in-an-array/FindTheSmallestThreeElementsInAnArray.swift b/program/program/find-the-smallest-three-elements-in-an-array/FindTheSmallestThreeElementsInAnArray.swift new file mode 100644 index 000000000..e63867d9f --- /dev/null +++ b/program/program/find-the-smallest-three-elements-in-an-array/FindTheSmallestThreeElementsInAnArray.swift @@ -0,0 +1,32 @@ +import Foundation + +func findSmallestThreeElements(arr: [Int]) -> [Int] { + guard arr.count >= 3 else { + print("Array should have at least 3 elements") + return [] + } + + var first = Int.max + var second = Int.max + var third = Int.max + + for num in arr { + if num < first { + third = second + second = first + first = num + } else if num < second { + third = second + second = num + } else if num < third { + third = num + } + } + + return [first, second, third] +} + +// Example usage +let arr = [12, 13, 1, 10, 34, 1] +let smallestThree = findSmallestThreeElements(arr: arr) +print("The smallest three elements are: \(smallestThree)")