Created
June 18, 2014 14:49
-
-
Save ariok/94e67f98625a69eb8902 to your computer and use it in GitHub Desktop.
Quicksort in Swift using Generics (Not in-place)
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
import Cocoa | |
func quicksort<T: Comparable>(array:T[])->T[] { | |
var less = T[](), equal = T[](), greater = T[]() | |
if array.count > 1{ | |
let pivot = array[0] | |
for x in array{ | |
switch(x){ | |
case (let v) where v < pivot: | |
less.append(v) | |
case (let v) where v > pivot: | |
greater.append(v) | |
default: | |
equal.append(x) | |
} | |
} | |
return (quicksort(less) + equal + quicksort(greater)); | |
}else{ | |
return array; | |
} | |
} | |
let randomString = ["bravo","alpha","aalpha","delta","charlie"]; | |
let sortedString = quicksort(randomString); | |
let randomInt = [10,30,2,15] | |
let sortedInt = quicksort(randomInt) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment