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


原创粉丝点击