iOS插入排序

来源:互联网 发布:淘宝虚假交易怎么清洗, 编辑:程序博客网 时间:2024/05/18 00:07
#import <Foundation/Foundation.h>@interface InsertSort : NSObject/// 直接插入排序+ (void)insertSort:(NSMutableArray *)list;/// 折半插入排序+ (void)binaryInsertSort:(NSMutableArray *)list;@end
#import "InsertSort.h"@implementation InsertSort+ (void)insertSort:(NSMutableArray *)list{    for (NSInteger i = 1; i< list.count; i++) {        NSInteger j = i;        NSInteger temp = [[list objectAtIndex:i]integerValue];        while (j>0 && temp <  [[list objectAtIndex:j - 1] integerValue]) {            [list replaceObjectAtIndex:j withObject:[list objectAtIndex:(j - 1)]];        }        [list replaceObjectAtIndex:j withObject:[NSNumber numberWithInteger:temp]];    }}+ (void)binaryInsertSort:(NSMutableArray *)list{    for (NSInteger i =1; i<list.count; i++) {        NSInteger temp = [[list objectAtIndex:i]integerValue];        NSInteger left = 0;        NSInteger right = i-1;        while (left <= right) {            NSInteger minddle = (left + right)/2;            if(temp < [[list objectAtIndex:minddle]integerValue]){                right = minddle - 1;            }else{                left = minddle + 1;            }        }        for (NSInteger j = i; j>left; j--) {            [list replaceObjectAtIndex:j withObject:[list objectAtIndex:j-1]];        }        [list replaceObjectAtIndex:left withObject:[NSNumber numberWithInteger:temp]];    }}@end


0 0