zoukankan      html  css  js  c++  java
  • 算法-三向字符串快速排序

    根据高位优先的字符串排序的思想我们可以改进快速排序算法,根据键的首字母进行三向切分,将两者结合起来就是可以理解的高效排序算法-三向字符串快速排序。三向字符串快速排序是一个字符串排序的通用算法,最多的情况适用于含有公共前缀的字符串。

    -(NSInteger)charAt:(NSString *)str index:(NSInteger)index{
        if (index<str.length) {
            return [str characterAtIndex:index]-97;
        }else{
            return -1;
        }
    }
    
    -(void)exchange:(NSMutableArray *)dataSource  first:(NSInteger)first  second:(NSInteger)second{
        NSString  *temp=dataSource[first];
        dataSource[first]=dataSource[second];
        dataSource[second]=temp;
    }
    
    -(void)sort:(NSMutableArray *)dataSource{
        [self sort:dataSource low:0 high:[dataSource count]-1 index:0];
    }
    
    -(void)sort:(NSMutableArray *)dataSource  low:(NSInteger)low  high:(NSInteger)high  index:(NSInteger)index{
        if (high<=low) {
            return;
        }
        NSInteger left=low,right=high;
        NSInteger  middle=[self charAt:dataSource[low] index:index];
        NSInteger i=low+1;
        while (i<=right) {
            NSInteger t=[self charAt:dataSource[i] index:index];
            if (t<middle) {
                [self exchange:dataSource first:left++ second:i++];
            }else if(t>middle){
                [self exchange:dataSource first:i second:right--];
            }else{
                i++;
            }
        }
        [self sort:dataSource low:low high:left-1 index:index];
        if (middle>=0) {
            [self sort:dataSource low:left high:right index:index+1];
        }
        [self sort:dataSource low:right+1 high:high index:index];
    }
    

     代码测试:

            Quick3String  *quick=[[Quick3String alloc]init];
            NSMutableArray  *dataSource=[[NSMutableArray alloc]initWithObjects:@"xiang",@"girl",@"he",@"fei",@"keso",@"fly",@"elephant",@"de",@"",@"she",@"elephant",nil];
              [quick sort:dataSource];
            [dataSource enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                NSLog(@"%@",obj);
            }];
            NSLog(@"技术交流群:%@",@"228407086");
            NSLog(@"博客园-FlyElephant:http://www.cnblogs.com/xiaofeixiang");
    

     测试效果:

  • 相关阅读:
    Python自定义web框架、Jinja2
    Django初探(模板渲染、模板语音、simple_tag、母版子版、静态配置文件)
    多线程 threading
    python操作mysql
    sql 汉字转首字母拼音
    添加sql server约束
    NFS,Memcached,Tokyo tyrant实现session共享性能测试
    让Editplus自动格式化js、css、html。。。
    sql server中利用sql语句如何创建角色和用户
    asp网站文件夹权限设置
  • 原文地址:https://www.cnblogs.com/xiaofeixiang/p/4857404.html
Copyright © 2011-2022 走看看