您的位置:首页 > 产品设计 > UI/UE

NSMutaleArray Quick Sort

2017-06-20 15:35 281 查看
#import<Foundation/Foundation.h>

@interface NSMutableArray (QuickSort)

- (void)quickSortUsingComparator:(NSComparator)comparator;

@end

//
//  NSArray+Sort.m
//  Test
//
//  Created by Ansel on 2017/6/20.
//  Copyright © 2017年 Ansel. All rights reserved.
//

#import "NSMutableArray+QuickSort.h"

@implementation NSMutableArray (QuickSort)

- (void)quickSortUsingComparator:(NSComparator)comparator
{
    [[selfclass]quickSortForArray:selfwithStartIndex:0endIndex:[selfcount]
-1comparator:comparator];
}

#pragma mark - PrivateMethod

+ (void)quickSortForArray:(NSMutableArray *)array withStartIndex:(NSInteger)startIndex
endIndex:(NSInteger)endIndex comparator:(NSComparator)comparator
{
    NSInteger count = [arraycount];
    //异常处理
    if (!array || count <=0 || startIndex <0 || endIndex
>= count || !comparator) {
        return;
    }
    
    //递归结束
    if (startIndex == endIndex) {
        return;
    }
    
    NSInteger index = [self partitionForArray:arraywithStartIndex:startIndexendIndex:endIndexcomparator:comparator];
    if (index > startIndex) {
        [self quickSortForArray:arraywithStartIndex:startIndexendIndex:index
-1comparator:comparator];
    }
    
    if (index < endIndex) {
        [self quickSortForArray:arraywithStartIndex:index
+1endIndex:endIndexcomparator:comparator];
    }
}

+ (NSInteger)partitionForArray:(NSMutableArray *)array withStartIndex:(NSInteger)startIndex
endIndex:(NSInteger)endIndex comparator:(NSComparator)comparator
{
    //把数组最后的元素作为比较,findIndex就是元素最后位置
    NSInteger findIndex = startIndex -1;
    
    //把小的数据放到findIndex之前,大的放到之后
    for (NSInteger index = startIndex; index < endIndex; index++) {
        if (comparator(array[index], array[endIndex]) !=NSOrderedDescending) {
           
findIndex++;
            
            if (findIndex != index) {
               
[array exchangeObjectAtIndex:findIndexwithObjectAtIndex:index];
           
}
        }
    }
    
    //把最后一个元素放到争取的位置
    ++findIndex;
    [array exchangeObjectAtIndex:findIndexwithObjectAtIndex:endIndex];
    
    return findIndex;
}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: