Skip to content

Instantly share code, notes, and snippets.

@henrytkirk
Created December 15, 2014 02:04
Show Gist options
  • Save henrytkirk/bff370549999977eadfd to your computer and use it in GitHub Desktop.
Save henrytkirk/bff370549999977eadfd to your computer and use it in GitHub Desktop.
QuickSort with Objective-C
- (NSArray *)quickSortWithArray:(NSArray *)array {
if (array.count == 0) {
return array;
}
// Use first item as pivot
NSNumber *pivot = array[0];
// Creat temp arrays to hold values
NSMutableArray *leftArray = [NSMutableArray array];
NSMutableArray *rightArray = [NSMutableArray array];
// All elements less than pivot go to left array
// All elements greater than pivot go to right array
for (NSInteger i = 1; i < array.count; i++) {
NSNumber *item = array[i];
if (item.integerValue < pivot.integerValue) {
[leftArray addObject:item];
} else {
[rightArray addObject:item];
}
}
// Recursively build merged arrays
NSArray *leftMerged = [self quickSortWithArray:leftArray];
NSArray *rightMerged = [self quickSortWithArray:rightArray];
// Build final array
NSMutableArray *finalArray = [NSMutableArray array];
[finalArray addObjectsFromArray:leftMerged];
[finalArray addObject:pivot];
[finalArray addObjectsFromArray:rightMerged];
return finalArray;
}
@henrytkirk
Copy link
Author

This assumes an array of NSNumber objects.

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