转载

算法-键索引计数法

键索引计数法适合于整数分为较小的简单排序方法,基本的步骤分为四步:

1.统计每个分类出现的次数;

2.将分类的次数转换为对应的索引;

3.通过中间数组按照分类的权重对原始数组排序;

4.将排序之后中间数组赋值给原始数组;

基础定义

首先定义排序需要的需要类:

@interface keyIndexModel:NSObject  @property  (assign,nonatomic)  NSInteger  key;  @property  (strong,nonatomic)  NSString  *value;  -(instancetype)initWithKeyValue:(NSInteger)key  value:(NSString *)value;  @end  @interface KeyIndexSort : NSObject  -(void)sort:(NSMutableArray *)dataSource categoryNumber:(NSInteger)number;  @end

实现具体排序方法:

-(void)sort:(NSMutableArray *)dataSource categoryNumber:(NSInteger)number{  NSInteger  len=[dataSource count];  NSMutableArray  *tempArr=[[NSMutableArray alloc]initWithCapacity:1];  //http://www.cnblogs.com/xiaofeixiang/  for (NSInteger i=0; i<len; i++) {   [tempArr addObject:[NSNull null]];  }  NSMutableArray *count=[[NSMutableArray alloc]initWithCapacity:1];  for (NSInteger i=0; i<number+1; i++) {   [count addObject:[NSNumber numberWithInteger:0]];  }  //统计每个分类的次数  for (NSInteger i=0;i<len; i++) {   keyIndexModel  *model=dataSource[i];   count[model.key+1]=[NSNumber numberWithInteger:[count[model.key+1] integerValue]+1];  }  //将出现的次数转换为索引,第一组3次,第二组5次,因此对应第三组开始的索引是8  for (NSInteger j=0; j<number; j++) {   count[j+1]=[NSNumber numberWithInteger:[count[j] integerValue]+[count[j+1] integerValue]];  }  //将元素从上到下分类  for (NSInteger m=0; m<len; m++) {   keyIndexModel  *model=dataSource[m];   tempArr[[count[model.key] integerValue]]=model;   count[model.key]=[NSNumber numberWithInteger:[count[model.key] integerValue]+1];  }  //重新排序赋值  for (NSInteger i=0; i<len; i++) {   dataSource[i]=tempArr[i];  } } 

排序测试

NSMutableArray  *dataSource=[[NSMutableArray alloc]initWithCapacity:1]; [dataSource addObject: [[keyIndexModel alloc]initWithKeyValue:0 value:@"FlyElephant"]]; [dataSource addObject: [[keyIndexModel alloc]initWithKeyValue:1 value:@"keso"]]; [dataSource addObject: [[keyIndexModel alloc]initWithKeyValue:2 value:@"中山郎"]]; [dataSource addObject: [[keyIndexModel alloc]initWithKeyValue:3 value:@"http://www.cnblogs.com/xiaofeixiang/"]]; [dataSource addObject: [[keyIndexModel alloc]initWithKeyValue:3 value:@"iOS技术交流:228407086"]]; [dataSource addObject: [[keyIndexModel alloc]initWithKeyValue:2 value:@"北京"]]; [dataSource addObject: [[keyIndexModel alloc]initWithKeyValue:1 value:@"上海"]]; [dataSource addObject: [[keyIndexModel alloc]initWithKeyValue:3 value:@"深圳"]]; [dataSource addObject: [[keyIndexModel alloc]initWithKeyValue:2 value:@"广州"]]; [dataSource addObject: [[keyIndexModel alloc]initWithKeyValue:0 value:@"河南"]]; KeyIndexSort  *indexSort=[[KeyIndexSort alloc]init]; [indexSort sort:dataSource categoryNumber:5];  [dataSource enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {   keyIndexModel  *model=obj;   NSLog(@"%ld--%@",idx,model.value);  }]; 

排序结果:

算法-键索引计数法

正文到此结束
Loading...