Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ariok/94e67f98625a69eb8902 to your computer and use it in GitHub Desktop.
Save ariok/94e67f98625a69eb8902 to your computer and use it in GitHub Desktop.
Quicksort in Swift using Generics (Not in-place)
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