zoukankan      html  css  js  c++  java
  • 算法-低位优先的字符串排序

    低位优先的字符串排序相当于是对键索引计数方法的一个扩展,主要用于处理固定长度字符串,比如说手机号,固定电话,银行卡卡号,字符串的长度为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");
    

    效果如下:

  • 相关阅读:
    SpringBoot中Word转PDF
    使用Word模板导出标准表Word样式文件
    Chrome 80及以上版本 中 Iframe 跨域 Cookie 的 Samesite 问题
    Visual Studio 2022 Key
    《HelloGitHub》第 69 期
    重玩 40 年前的经典游戏小蜜蜂,这次通关了源码
    那些年的开源项目,你跑起来了吗?
    图片处理看这篇就完了「GitHub 热点速览 v.21.48」
    年底巩固下 CS 知识「GitHub 热点速览 v.21.49」
    误入 GitHub 游戏区,意外地收获颇丰
  • 原文地址:https://www.cnblogs.com/xiaofeixiang/p/4855578.html
Copyright © 2011-2022 走看看