堆排序的思想
利用大頂堆(小頂堆)堆頂記錄的是最大關(guān)鍵字(最小關(guān)鍵字)這一特性,使得每次從無序中選擇最大記錄(最小記錄)變得簡單。
其基本思想為(大頂堆):
將初始待排序關(guān)鍵字序列(R1,R2....Rn)構(gòu)建成大頂堆,此堆為初始的無序區(qū);
將堆頂元素R[1]與最后一個元素R[n]交換,此時得到新的無序區(qū)(R1,R2,......Rn-1)和新的有序區(qū)(Rn),且滿足R[1,2...n-1]<=R[n];
由于交換后新的堆頂R[1]可能違反堆的性質(zhì),因此需要對當(dāng)前無序區(qū)(R1,R2,......Rn-1)調(diào)整為新堆,然后再次將R[1]與無序區(qū)最后一個元素交換,得到新的無序區(qū)(R1,R2....Rn-2)和新的有序區(qū)(Rn-1,Rn)。不斷重復(fù)此過程直到有序區(qū)的元素個數(shù)為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{
//建立堆,從最底層的父節(jié)點(diǎn)開始
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