码迷,mamicode.com
首页 > 编程语言 > 详细

算法-低位优先的字符串排序

时间:2015-10-05 19:31:31      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:

低位优先的字符串排序相当于是对键索引计数方法的一个扩展,主要用于处理固定长度字符串,比如说手机号,固定电话,银行卡卡号,字符串的长度为N,从右向左开始进行每个键作为值开始遍历,实现比较简单:

-(void)lowSort:(NSMutableArray *)dataSource singleLength:(NSInteger)len
{
    NSInteger  sourceCount=[dataSource count];
    NSInteger R=256;
    NSMutableArray  *tempArr=[[NSMutableArray alloc]initWithCapacity:1];
    for (NSInteger i=0; i<sourceCount; i++) {
        [tempArr addObject:[NSNull null]];
    }
    for (NSInteger d=len-1; d>=0; d--) {
        NSMutableArray  *count=[[NSMutableArray alloc]initWithCapacity:1];
        for (NSInteger i=0; i<R+1; i++) {
            [count addObject:[NSNumber numberWithInteger:0]];
        }
        //统计频率
        for (NSInteger i=0; i<sourceCount; i++) {
            NSString  *str=[dataSource objectAtIndex:i];
            NSInteger  charValue=[str characterAtIndex:d]-48;
            count[charValue+1]=[NSNumber numberWithInteger:[count[charValue+1] integerValue]+1];
        }
        for (NSInteger j=0; j<R; j++) {
            count[j+1]=[NSNumber numberWithInteger:[count[j] integerValue]+[count[j+1] integerValue]];
        }
        //将元素从上到下分类
        for (NSInteger m=0; m<sourceCount; m++) {
            NSString  *str=[dataSource objectAtIndex:m];
            NSInteger  charValue=[str characterAtIndex:d]-48;
            tempArr[[count[charValue] integerValue]]=dataSource[m];
            count[charValue]=[NSNumber numberWithInteger:[count[charValue] integerValue]+1];
        }
        //重新排序赋值
        for (NSInteger i=0; i<sourceCount; i++) {
            dataSource[i]=tempArr[i];
        }
    }
}

 代码测试:

        LSD  *lsd=[[LSD alloc]init];
        NSMutableArray  *dataSource=[[NSMutableArray alloc]initWithObjects:@"12345",@"23456",@"78901",@"89764",@"12345",@"45678",@"89794",@"89754",@"64532",@"69784",nil];
        [lsd lowSort:dataSource singleLength:7];
        [dataSource enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSLog(@"%@",obj);
        }];
        NSLog(@"技术交流群:%@",@"228407086");
        NSLog(@"博客园-FlyElephant:http://www.cnblogs.com/xiaofeixiang");

效果如下:

技术分享

算法-低位优先的字符串排序

标签:

原文地址:http://www.cnblogs.com/xiaofeixiang/p/4855578.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!