Skip to content

Instantly share code, notes, and snippets.

@marioeguiluz
Last active September 21, 2016 00:49
Show Gist options
  • Save marioeguiluz/d6af7de44cbaea8386dc to your computer and use it in GitHub Desktop.
Save marioeguiluz/d6af7de44cbaea8386dc to your computer and use it in GitHub Desktop.
Insertion Sort Swift
//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;
}
@marioeguiluz
Copy link
Author

Updated for Swift 3.0 with Generics

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment