美文网首页知识点梳理
iOS基本算法之二分法排序

iOS基本算法之二分法排序

作者: 深山问 | 来源:发表于2016-04-29 13:33 被阅读358次

    话不多说,上代码

    Objective-C 实现
    - (NSArray *)binarySort:(NSArray *)array {
        NSMutableArray *result = [array mutableCopy];
        for (NSInteger index = 0; index < result.count; index++) {
            NSInteger start, end, middle;
            start  = 0;
            end    = index - 1;
            middle = 0;
            NSInteger temp = [result[index] integerValue];
            while (start <= end) {
                middle = (start + end) / 2;
                if ([array[middle] integerValue] >  temp) {
                    end = middle - 1;
                }else{
                    start = middle + 1;
                }
            }
            for (NSInteger j = index - 1; j > end; j--) {
                result[j+1] = result[j];
            }
            [result replaceObjectAtIndex:end+1 withObject:[NSNumber numberWithInteger:temp]];
        }
        return [result copy];
    }
    

    对以下数组的排序结果如下:

    //源数据
    NSArray *source = @[@12,@3,@23,@34,@35,@99,@98,@43];
    //输出结果
    **2016-04-29 13:34:20.769 SHENDONGTEST[74979:1587742] source = (**
      12,
      3,
      23,
      34,
      35,
      99,
      98,
      43
    )
    **2016-04-29 13:34:20.769 SHENDONGTEST[74979:1587742] result = (**
       3,
       12,
       23,
       34,
       35,
       43,
       98,
       99
    )
    

    Swift实现(swift2.0)

    //***********************二分法排序**************************
    //1. 源数据
    let sources = [12,3,23,34,35,99,98,43]
    //2. 二分法排序算法
    func binarySort(array: [Int]) -> [Int]{
        var source = array
        for index in 0..<source.count{
            var start  = 0
            var end    = index - 1
            var middle = 0
            let temp   = source[index]
            while(start <= end){
                middle = (start + end) / 2
                if(array[middle] > temp){ //待排序元素在需排序数组的左边
                    end = middle - 1
                }else{
                    start = middle + 1
                }
            }
            for tempIndex in (end+1)..<index{ //找到了待插入的位置,然后将这个位置以后的所有元素相后移动
                source[tempIndex+1] = source[tempIndex]
            }
            source[end+1] = temp
        }
        return source
    }
    //3.输出实现
    print(binarySort(sources))
    //4.终端输出结果
    **Hello, World!**
    **[3, 12, 23, 34, 35, 43, 98, 98]**
    **Program ended with exit code: 0**
    

    相关文章

      网友评论

      • 和珏猫:挺好,就喜欢直接开整的,但是最好加一些注释或者语言描述

      本文标题:iOS基本算法之二分法排序

      本文链接:https://www.haomeiwen.com/subject/cxahrttx.html