Skip to content

Instantly share code, notes, and snippets.

@0xMarK
Last active November 30, 2020 09:24
Show Gist options
  • Save 0xMarK/42c5b60251480d16ae2979d14f9bc01f to your computer and use it in GitHub Desktop.
Save 0xMarK/42c5b60251480d16ae2979d14f9bc01f to your computer and use it in GitHub Desktop.
Insertion Sort
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