iOS堆排序

2017-05-08  本文已影响165人  oceanfish

堆排序的思想

利用大顶堆(小顶堆)堆顶记录的是最大关键字(最小关键字)这一特性,使得每次从无序中选择最大记录(最小记录)变得简单。
其基本思想为(大顶堆):
将初始待排序关键字序列(R1,R2....Rn)构建成大顶堆,此堆为初始的无序区;
将堆顶元素R[1]与最后一个元素R[n]交换,此时得到新的无序区(R1,R2,......Rn-1)和新的有序区(Rn),且满足R[1,2...n-1]<=R[n];
由于交换后新的堆顶R[1]可能违反堆的性质,因此需要对当前无序区(R1,R2,......Rn-1)调整为新堆,然后再次将R[1]与无序区最后一个元素交换,得到新的无序区(R1,R2....Rn-2)和新的有序区(Rn-1,Rn)。不断重复此过程直到有序区的元素个数为n-1,则整个排序过程完成。

//
//  HeapViewController.m
//  AllStack
//
//  Created by kang.yu.sh on 2017/5/8.
//  Copyright © 2017年 kang.yu.sh. All rights reserved.
//

#import "HeapViewController.h"

@interface HeapViewController (){
    NSMutableArray *list;
}

@end

@implementation HeapViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    list = [NSMutableArray arrayWithObjects:@"23", @"65", @"12", @"3", @"8", @"76", @"345", @"90", @"21",
                     @"75", @"34", @"61", nil];
    NSInteger listLen = list.count;
    
    [self heapSort:list len:listLen];
}

- (void)heapSort:(NSMutableArray *)heapList len:(NSInteger)len{
    //建立堆,从最底层的父节点开始
    NSLog(@"%@", heapList);
    for(NSInteger i = (heapList.count/2 -1); i>=0; i--)
        [self adjustHeap:heapList location:i len:heapList.count];
    
    for(NSInteger i = heapList.count -1; i >= 0; i--){
        //R[N] move EndLocation
        NSInteger maxEle = ((NSString *)heapList[0]).integerValue;
        heapList[0] = heapList[i];
        heapList[i] = @(maxEle).stringValue;
        
        [self adjustHeap:heapList location:0 len:i];
    }
}

- (void)adjustHeap:(NSMutableArray *)heapList location:(NSInteger)p len:(NSInteger)len{
    NSInteger curParent = ((NSString *)heapList[p]).integerValue;
    NSInteger child = 2*p + 1;
    while (child < len) {
        //left < right
        if (child+1 < len && ((NSString *)heapList[child]).integerValue < ((NSString *)heapList[child+1]).integerValue) {
            child ++;
        }
        if (curParent < ((NSString *)heapList[child]).integerValue) {
            heapList[p] = heapList[child];
            p = child;
            child = 2*p + 1;
        }
        else
            break;
    }
    heapList[p] = @(curParent).stringValue;
    
    NSLog(@">>>: %@", heapList);
}


@end

上一篇 下一篇

猜你喜欢

热点阅读