Created
April 24, 2015 15:50
-
-
Save pkh/363c27afc310fe1563f8 to your computer and use it in GitHub Desktop.
Quicksort Algorithm in Objective-C
This file contains hidden or 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
- (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