iOS基本算法之二分法排序

话不多说,上代码

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.. temp){ //待排序元素在需排序数组的左边
                end = middle - 1
            }else{
                start = middle + 1
            }
        }
        for tempIndex in (end+1)..

你可能感兴趣的:(iOS基本算法之二分法排序)