Skip to content

Instantly share code, notes, and snippets.

@0xABCCBA
Created August 30, 2018 06:08
Show Gist options
  • Save 0xABCCBA/300bebcf05824a0a07901b3f92c4a8d8 to your computer and use it in GitHub Desktop.
Save 0xABCCBA/300bebcf05824a0a07901b3f92c4a8d8 to your computer and use it in GitHub Desktop.
InsertionSort
/// from swift-algorithm-club
/// O(n^2)
func insertionSort(_ array: [Int]) -> [Int] {
var a = array
for x in (1..<a.count) {
var y = x
while y > 0 && a[y] < a[y - 1] {
a.swapAt(y - 1, y)
y -= 1
}
}
return a
}
func lessSwap(_ array: [Int]) -> [Int] {
var a = array
for x in 1..<a.count {
var y = x
let temp = a[y]
while y > 0 && temp < a[y - 1] {
a[y] = a[y - 1]
y -= 1
}
a[y] = temp
}
return a
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment