Last active
August 29, 2015 14:06
-
-
Save ursooperduper/e938a64277be44ff13a3 to your computer and use it in GitHub Desktop.
Insertion Sort algorithm written in Swift
This file contains hidden or 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
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