Created
December 15, 2014 02:04
-
-
Save henrytkirk/bff370549999977eadfd to your computer and use it in GitHub Desktop.
QuickSort with Objective-C
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
- (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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This assumes an array of NSNumber objects.