低位優先的字符串排序相當于是對鍵索引計數方法的一個擴展,主要用于處理固定長度字符串,比如說手機號,固定電話,銀行卡卡號,字符串的長度為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");
效果如下: