Created
August 30, 2018 06:08
-
-
Save 0xABCCBA/300bebcf05824a0a07901b3f92c4a8d8 to your computer and use it in GitHub Desktop.
InsertionSort
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
/// 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