NSMutableArray Merge Sort
来源:互联网 发布:t恤印花 知乎 编辑:程序博客网 时间:2024/05/15 23:43
#import <Foundation/Foundation.h>
@interface NSMutableArray (MergeSort)
- (void)mergeSortUsingComparator:(NSComparator)comparator;
@end
#import "NSMutableArray+MergeSort.h"
@implementation NSMutableArray (MergeSort)
- (void)mergeSortUsingComparator:(NSComparator)comparator
{
[[self class] mergeSortForArray:self withStartIndex:0 endIndex:[self count] - 1 comparator:comparator];
}
#pragma mark - PrivateMethod
+ (void)mergeSortForArray:(NSMutableArray *)array withStartIndex:(NSInteger)startIndex endIndex:(NSInteger)endIndex comparator:(NSComparator)comparator
{
NSInteger count = [array count];
if (!array || count <= 1 || startIndex < 0 || endIndex >= count || !comparator) {
return;
}
NSInteger middleIndex = (startIndex + endIndex) / 2;
if (startIndex < middleIndex) {
[self mergeSortForArray:array withStartIndex:startIndex endIndex:middleIndex comparator:comparator];
}
if (middleIndex+ 1 < endIndex) {
[self mergeSortForArray:array withStartIndex:middleIndex + 1 endIndex:endIndex comparator:comparator];
}
[self mergeDataForArray:array withStartIndex:startIndex middleIndex:middleIndex endIndex:endIndex comparator:comparator];
}
+ (void)mergeDataForArray:(NSMutableArray *)array withStartIndex:(NSInteger)startIndex middleIndex:(NSInteger)middleIndex endIndex:(NSInteger)endIndex comparator:(NSComparator)comparator
{
NSInteger left = startIndex;
NSInteger right = middleIndex + 1;
NSMutableArray *sortArray = @[].mutableCopy;
while (left <= middleIndex && right <= endIndex) {
if (comparator(array[left], array[right]) == NSOrderedAscending) {
[sortArray addObject:array[left]];
left++;
} else {
[sortArray addObject:array[right]];
right++;
}
}
//添加left剩余的数据到sortArray
for (NSInteger index = left; index <= middleIndex; index++) {
[sortArray addObject:array[index]];
}
//添加right剩余的数据到sortArray
for (NSInteger index = right; index <= endIndex; index++) {
[sortArray addObject:array[index]];
}
//把替换sortArray替换到array
for (NSInteger index = startIndex; index <= endIndex; index++) {
[array replaceObjectAtIndex:index withObject: sortArray[index - startIndex]];
}
sortArray = nil;
}
@end
- NSMutableArray Merge Sort
- NSMutableArray Heap Sort
- Merge Sort
- Merge sort
- merge sort
- merge sort
- merge sort
- Merge Sort
- merge sort
- Merge Sort
- Merge Sort
- merge sort
- Merge Sort
- Merge sort
- Merge-sort
- Merge Sort
- Merge sort
- Merge Sort
- Qt使用Qtextstream进行换行操作
- webview详解
- VoIP基本概念(9):回声消除技术
- 复合索引的应用场景
- JNDI详解
- NSMutableArray Merge Sort
- Protobuf协议格式详解
- 一个java购物车模型
- Windows7(64)+anaconda2(python2.7)安装pybrain包详细步骤
- 飞机大战(四)
- ###########有用**********如何选择优化器 optimizer
- shell工具篇之grep
- React -- 表单
- RxJava2详解(二)--操作符