Skip to content

Instantly share code, notes, and snippets.

@voidet
Created December 7, 2014 00:24
Show Gist options
  • Save voidet/cc3a8d3a8d198bf87040 to your computer and use it in GitHub Desktop.
Save voidet/cc3a8d3a8d198bf87040 to your computer and use it in GitHub Desktop.
Swift Sorting Algorithms
import Foundation
extension Int {
func times(closure:(Int)->Void) {
for i in 0...self {
closure(i)
}
}
}
var hops = [7, 3, 2, 5, 3, 15, 6, 7, 6, 4, 3, 0, 3, 10];
func insertSort(var hops:[Int]) -> [Int] {
println("------- INSERTION SORT --------")
println(hops)
(hops.count - 1).times { (var i) in
var x = i
while (x - 1 >= 0 && hops[x - 1] > hops[x]) {
var tmp = hops[x - 1]
hops[x - 1] = hops[x]
hops[x] = tmp
x--
}
println(hops)
}
return hops
}
func bubbleSort(var hops:[Int]) -> [Int] {
println("------- BUBBLE SORT --------")
println(hops)
(hops.count - 2).times { i in
(hops.count - 2 - i).times { x in
if (hops[x] > hops[x + 1]) {
var tmp = hops[x + 1]
hops[x + 1] = hops[x]
hops[x] = tmp
}
}
println(hops)
}
return hops
}
func quickSort(var hops:Array<Int>) -> Array<Int> {
if (hops.count <= 1) {
return hops
}
var pivot = hops.removeAtIndex(0)
var leftBucket:[Int] = []
var rightBucket:[Int] = []
(hops.count - 1).times { i in
if (hops[i] <= pivot) {
leftBucket.append(hops[i])
} else {
rightBucket.append(hops[i])
}
}
var mergedArray:[Int] = []
println("left \(leftBucket)")
mergedArray += quickSort(leftBucket)
mergedArray += [pivot]
println("right \(rightBucket)")
mergedArray += quickSort(rightBucket)
return mergedArray
}
func mergeSort(input:Array<Int>) -> Array<Int> {
if (input.count <= 1) {
return input
}
let mid = Int(floor(Double(input.count / 2)))
let left = Array(input[0..<mid])
let right = Array(input[mid..<input.count])
println("left \(left)")
let leftSide = mergeSort(left)
println("right \(right)")
let rightSide = mergeSort(right)
return sortThem(leftSide, rightSide)
}
func sortThem(left:Array<Int>, right:Array<Int>) -> Array<Int> {
var sortedArray:[Int] = []
var leftCount = 0
var rightCount = 0
(left.count + right.count).times { i in
if (leftCount < left.count && (rightCount >= right.count || left[leftCount] <= right[rightCount])) {
sortedArray.append(left[leftCount++])
} else if (rightCount < right.count && (leftCount >= left.count || right[rightCount] < left[leftCount])) {
sortedArray.append(right[rightCount++])
}
}
return sortedArray
}
insertSort(hops)
println("------- MERGE SORT --------")
mergeSort(hops)
println("------- QUICK SORT --------")
quickSort(hops)
bubbleSort(hops)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment