iOS 选择排序和堆排序

2019-10-12  本文已影响0人  雪中夜归人

选择排序(Selection Sort)

  选择排序的核心思想:找到数组中最大值(或者最小),然后跟最后元素交换。(去除最后元素,重复操作)

- (void)sort
{
    NSInteger count = self.sortArray.count;
    for (NSInteger end = count - 1; end >= 0; end--) {
        NSInteger maxIndex = 0;
        for (NSInteger begain = 1; begain <= end; begain++) {
            if ([self compareObjcet:self.sortArray[maxIndex] anotherObject:self.sortArray[begain]] == YES) {
                maxIndex = begain;
            }
        }
        if (maxIndex != end) {
            [self swapObjectWithIndex:maxIndex anotherIndex:end];
        }
    }
}

  显然选择排序的核心就是寻找最大(或者最小值)。此上代码用的最简单的一种方式---遍历查找。

堆排序(Heap Sort)

  那么有一种结构能够更快的查找到最大最小值,那就是大顶堆或者小顶堆。那么这种方式的排序就是堆排序(Heap Sort),其实质上可以看成是选择排序的优化。

第一步:将数组建堆,而建堆的核心是数组中元素下沉(site down)

// 建堆操作
- (void)buildMaxHeap
{
    NSInteger arrayCount = self.sortArray.count;
    for(NSInteger i = arrayCount - 1; i > 0; i = i - 2){
        NSInteger currentIndex = (i + 1) / 2 - 1;
        [self siteDownWithIndex:currentIndex heapSize:arrayCount];
    }
}
//  指定下标的数据下沉
- (void)siteDownWithIndex:(NSInteger)index heapSize:(NSInteger)heapSize
{
    if (heapSize <= 1) {
        return;
    }
    NSInteger leftIndex = (index << 1) + 1;
    
    NSInteger rightIndex = (index << 1) + 2;
    
    id currentValue = self.sortArray[index];
    id leftValue = nil;
    id rightValue = nil;
    
    if (leftIndex >= heapSize) {
        return;
    }
    
    leftValue = self.sortArray[leftIndex];
    
    if (rightIndex < heapSize) {
        rightValue = self.sortArray[rightIndex];
        if ([self compareObjcet:currentValue anotherObject:leftValue] && [self compareObjcet:rightValue anotherObject:leftValue]) {
            [self swapObjectWithIndex:leftIndex anotherIndex:index];
            [self siteDownWithIndex:leftIndex heapSize:heapSize];
        }
        
        if ([self compareObjcet:currentValue anotherObject:rightValue] && [self compareObjcet:leftValue anotherObject:rightValue]) {
            [self swapObjectWithIndex:rightIndex anotherIndex:index];
            [self siteDownWithIndex:rightIndex heapSize:heapSize];
        }
        return;
    }
    if ([self compareObjcet:currentValue anotherObject:leftValue]) {
        [self swapObjectWithIndex:leftIndex anotherIndex:index];
    }
}

第二步:将堆顶元素与最后元素交换然后堆顶元素下沉,重新生成大顶堆

- (void)sort
{
    NSInteger arrayCount = self.sortArray.count;
    [self buildMaxHeap];
    
    for (NSInteger i = arrayCount - 1; i >= 1; i--) {
        [self swapObjectWithIndex:0 anotherIndex:i];
        [self siteDownWithIndex:0 heapSize:i];
    }
}

总结:选择排序和堆排序都可以看成是寻找最大值然后依次在数组中放好的过程。

上一篇 下一篇

猜你喜欢

热点阅读