Last active
December 2, 2015 01:48
-
-
Save antonio081014/e2cc6393c513f06fa2e4 to your computer and use it in GitHub Desktop.
This is the quicksort implementation written in 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 *)quicksort:(NSArray *)array |
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 *)quicksort:(NSArray *)array | |
{ | |
NSMutableArray *helper = [array mutableCopy]; | |
[self quicksort:helper from:0 to:array.count-1]; | |
return helper; | |
} | |
- (void)quicksort:(NSMutableArray *)array from:(NSInteger)left to:(NSInteger)right | |
{ | |
if(left >= right) return; | |
NSInteger mid = [self partitionArray:array from:left to:right]; | |
[self quicksort:array from:left to:mid-1]; | |
[self quicksort:array from:mid+1 to:right]; | |
} | |
- (NSInteger)partitionArray:(NSMutableArray *)array from:(NSInteger)left to:(NSInteger)right | |
{ | |
if(left + 1 == right) { | |
if([array[left] integerValue] > [array[right] integerValue]) { | |
NSNumber *tmp = array[left]; | |
array[left] = array[right]; | |
array[right] = tmp; | |
} | |
return left; | |
} | |
NSNumber *pivot = array[right]; | |
NSInteger p1 = left; | |
for(NSInteger j=left; j<right; j++) { | |
if([array[j] integerValue] < [pivot integerValue]) { | |
NSNumber *tmp = array[p1]; | |
array[p1] = array[j]; | |
array[j] = tmp; | |
p1 ++; | |
} | |
} | |
NSNumber *tmp = array[p1]; | |
array[p1] = array[right]; | |
array[right] = tmp; | |
return p1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment