Created
July 29, 2013 01:52
-
-
Save satoshin2071/6101712 to your computer and use it in GitHub Desktop.
objective-C QuickSort
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
#import <Foundation/Foundation.h> | |
@interface NSArray (quickSort) | |
- (NSArray*)quickSort; | |
@end |
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
#import "NSArray+quickSort.h" | |
@implementation NSArray (quickSort) | |
- (NSArray*)quickSort | |
{ | |
return [self quickSort:self]; | |
} | |
- (NSArray*)quickSort:(NSArray*)unsortedArray | |
{ | |
//要素数が1以下なら終了 | |
NSInteger numberOfElments = [unsortedArray count]; | |
if (numberOfElments <= 1) { | |
return unsortedArray; | |
} | |
//配列からpivotとってくる。 | |
NSNumber *pivot = [unsortedArray objectAtIndex:numberOfElments / 2]; | |
//pivotより大きい値と小さい値に分けた配列をそれぞれ生成 | |
NSMutableArray *lessArray = [[NSMutableArray alloc]initWithCapacity:numberOfElments]; | |
NSMutableArray *moreArray = [[NSMutableArray alloc]initWithCapacity:numberOfElments]; | |
for (NSNumber *value in unsortedArray) { | |
if ([value floatValue] < [pivot floatValue] ) { | |
[lessArray addObject:value]; | |
}else if([value floatValue] > [pivot floatValue]){ | |
[moreArray addObject:value]; | |
} | |
} | |
//再帰呼び出ししてソートしていく。 | |
NSMutableArray *sortedArray = [[NSMutableArray alloc]initWithCapacity:numberOfElments]; | |
[sortedArray addObjectsFromArray: [self quickSort:lessArray]]; | |
[sortedArray addObject:pivot]; | |
[sortedArray addObjectsFromArray:[self quickSort:moreArray]]; | |
return [sortedArray copy]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment