• 算法-三向字符串快速排序


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

    -(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");
    

     测试效果:

  • 相关阅读:
    js画矩形
    js加载pdf截屏生成图片调用ocr识别成文字
    C#List或者Set集合相同的key合并Value的值
    Oracle学习笔记读懂执行计划(十八)
    Java 阻塞队列
    SpringMVC(三):参数绑定、输入输出转换
    springMVC(二): @RequestBody @ResponseBody 注解实现分析
    Spring Security 4.2.3 Filters 解析
    MySQL 加锁处理分析
    Innodb semi-consistent 简介
  • 原文地址:https://www.cnblogs.com/xiaofeixiang/p/4857404.html
Copyright © 2020-2023  润新知