This repository has been archived by the owner on Jul 10, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 167
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
32 additions
and
0 deletions.
There are no files selected for viewing
32 changes: 32 additions & 0 deletions
32
.../find-the-smallest-three-elements-in-an-array/FindTheSmallestThreeElementsInAnArray.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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)") |