Last active
September 21, 2016 00:49
-
-
Save marioeguiluz/d6af7de44cbaea8386dc to your computer and use it in GitHub Desktop.
Insertion Sort 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
//Helper function to exchange position in one array | |
//From: http://stackoverflow.com/questions/24077880/swift-make-method-parameter-mutable | |
func exchange<T>(_ data: inout [T], i:Int, j:Int) { | |
let temp:T = data[i] | |
data[i] = data[j] | |
data[j] = temp | |
} | |
//Insertion Sort of an array of integers | |
func insertionSort<T:Comparable>(_ unsortedArray:Array<T>)->Array<T>{ | |
var unsortedArray = unsortedArray | |
if(unsortedArray.count<2) { | |
return unsortedArray | |
} | |
for j in 1 ..< unsortedArray.count { | |
var i = j | |
while i>0 && unsortedArray[i-1]>unsortedArray[i] { | |
exchange(&unsortedArray, i: i-1, j: i) | |
i -= 1; | |
} | |
} | |
return unsortedArray; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated for Swift 3.0 with Generics