Last active
November 30, 2020 09:24
-
-
Save 0xMarK/42c5b60251480d16ae2979d14f9bc01f to your computer and use it in GitHub Desktop.
Insertion Sort
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
func insertionSort(_ array: [Int]) -> [Int] { | |
guard array.count > 1 else { return array } | |
var sorted = array | |
for i in 1..<array.count { | |
let current = sorted[i] | |
var next: Int? | |
for j in 0...i { | |
if next == nil, | |
current < sorted[j] { | |
next = current | |
} | |
if let newValue = next { | |
next = sorted[j] | |
sorted[j] = newValue | |
} | |
} | |
} | |
return sorted | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment