Last active
September 17, 2015 10:07
-
-
Save chriseidhof/c03a04a503f9744071c9 to your computer and use it in GitHub Desktop.
qsort
This file contains 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 <Foundation/Foundation.h> | |
int stringComp(const void *a, const void *b) { | |
NSString *aO = *(NSString *__autoreleasing*)a; | |
NSString *bO = *(NSString *__autoreleasing*)b; | |
return [aO caseInsensitiveCompare:bO]; | |
} | |
int main(int argc, const char * argv[]) { | |
@autoreleasepool { | |
NSString * __autoreleasing *array; | |
array = (NSString* __autoreleasing*) malloc(sizeof(NSString*)*20); | |
for(int i = 0; i < 20; i++) { | |
array[i] = [NSString stringWithFormat:@"%d", arc4random() % 100]; | |
} | |
qsort(array, 20, sizeof(NSString*), stringComp); | |
NSArray* result = [NSArray arrayWithObjects:array count:20]; | |
free(array); | |
NSLog(@"%@", result); | |
} | |
return 0; | |
} |
This file contains 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 Foundation | |
extension Comparable { | |
static func compare(l: UnsafePointer<Void>, r: UnsafePointer<Void>) -> Int32 { | |
let leftPointer: Self = UnsafePointer(l).memory | |
let rightPointer: Self = UnsafePointer(r).memory | |
if leftPointer < rightPointer { return -1 } | |
if leftPointer == rightPointer { return 0 } | |
return 1 | |
} | |
} | |
func cmp(thunk: UnsafeMutablePointer<Void>, l: UnsafePointer<Void>, r: UnsafePointer<Void>) -> Int32 { | |
let comparisonFunction: (UnsafePointer<Void>, UnsafePointer<Void>) -> Int32 = UnsafePointer(thunk).memory | |
return comparisonFunction(l,r) | |
} | |
func quickSort<A: Comparable>(var array: [A]) -> [A] { | |
var myFunc = A.compare | |
qsort_r(&array, array.count, strideof(A), &myFunc, cmp) | |
return array | |
} | |
let myArray = ["Hello", "ABC", "world", "abc"] | |
print(quickSort(myArray)) | |
print(myArray) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment