Skip to content

Instantly share code, notes, and snippets.

@ursooperduper
Last active August 29, 2015 14:06
Show Gist options
  • Save ursooperduper/e938a64277be44ff13a3 to your computer and use it in GitHub Desktop.
Save ursooperduper/e938a64277be44ff13a3 to your computer and use it in GitHub Desktop.
Insertion Sort algorithm written in Swift
typealias ArrayInt = Array<Int>
func lt(a: Int, b: Int) -> Bool {
return a < b
}
func gt(a: Int, b: Int) -> Bool {
return a > b
}
func insertionSort(arr: ArrayInt, comp: (Int, Int) -> Bool) -> ArrayInt {
var key = 0
var j = 0
var i = 0
// create a copy of the array to work with
var new_arr = arr
for j = 1; j < new_arr.count; ++j {
key = new_arr[j]
i = j - 1
//while i >= 0 && new_arr[i] > key {
while i >= 0 && comp(new_arr[i], key) {
new_arr[i + 1] = new_arr[i]
i = i - 1
}
new_arr[i + 1] = key
}
return new_arr
}
var myArr: [Int] = [31, 41, 59, 26, 41, 58]
insertionSort(myArr, gt)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment