Skip to content

Instantly share code, notes, and snippets.

@pkh
Created April 24, 2015 15:50
Show Gist options
  • Save pkh/363c27afc310fe1563f8 to your computer and use it in GitHub Desktop.
Save pkh/363c27afc310fe1563f8 to your computer and use it in GitHub Desktop.
Quicksort Algorithm in Objective-C
- (void)sortMyArray
{
NSMutableArray *unsorted = [NSMutableArray arrayWithArray:@[@67, @1, @14, @22, @77, @23, @21, @17, @99, @107, @89, @20]];
NSLog(@"Unsorted:");
NSLog(@"%@",unsorted);
NSMutableArray *sorted = [self quickSort:unsorted];
NSLog(@"Sorted:");
NSLog(@"%@",sorted);
}
- (NSMutableArray *)quickSort:(NSMutableArray *)unsortedArray
{
NSMutableArray *lessThanArray = [NSMutableArray new];
NSMutableArray *greaterThanArray = [NSMutableArray new];
if (unsortedArray.count < 1) {
return nil;
}
int randomPivotPoint = arc4random() % [unsortedArray count];
NSNumber *pivot = unsortedArray[randomPivotPoint];
[unsortedArray removeObjectAtIndex:randomPivotPoint];
for (NSNumber *num in unsortedArray) {
if (num < pivot) {
[lessThanArray addObject:num];
} else {
[greaterThanArray addObject:num];
}
}
NSMutableArray *sorted = [NSMutableArray new];
[sorted addObjectsFromArray:[self quickSort:lessThanArray]];
[sorted addObject:pivot];
[sorted addObjectsFromArray:[self quickSort:greaterThanArray]];
return sorted;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment