堆排序 (Heapsort)

本文通过一个具体的例子详细介绍了堆排序算法的全过程,包括堆的构建和排序两个主要步骤,并展示了每一步的操作细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文:http://en.wikipedia.org/wiki/Heap_sort


Let { 6, 5, 3, 1, 8, 7, 2, 4 } be the list that we want to sort from the smallest to the largest. (NOTE, for 'Building the Heap' step: Larger nodes don't stay below smaller node parents. They are swapped with parents, and then recursively checked if another swap is needed, to keep larger numbers above smaller numbers on the heap binary tree.)

An example on heapsort.

1. Build the heap

Heap newly added element swap elements
nil6 
65 
6, 53 
6, 5, 31 
6, 5, 3, 18 
6, 5, 3, 1, 8 5, 8
68, 3, 1, 5 6, 8
8, 6, 3, 1, 57 
8, 6, 3, 1, 5, 7 3, 7
8, 6, 7, 1, 5, 32 
8, 6, 7, 1, 5, 3, 24 
8, 6, 7, 1, 5, 3, 2, 4 1, 4
8, 6, 7, 4, 5, 3, 2, 1  

2. Sorting.

Heap swap elements delete element sorted array details
8, 6, 7, 4, 5, 3, 2, 18, 1  swap 8 and 1 in order to delete 8 from heap
1, 6, 7, 4, 5, 3, 2, 8 8 delete 8 from heap and add to sorted array
1, 6, 7, 4, 5, 3, 21, 7 8swap 1 and 7 as they are not in order in the heap
7, 6, 1, 4, 5, 3, 21, 3 8swap 1 and 3 as they are not in order in the heap
7, 6, 3, 4, 5, 1, 27, 2 8swap 7 and 2 in order to delete 7 from heap
2, 6, 3, 4, 5, 1, 7 78delete 7 from heap and add to sorted array
26, 3, 4, 5, 12, 6 7, 8swap 2 and 6 as they are not in order in the heap
6, 2, 3, 4, 5, 12, 5 7, 8swap 2 and 5 as they are not in order in the heap
6, 5, 3, 4, 2, 16, 1 7, 8swap 6 and 1 in order to delete 6 from heap
1, 5, 3, 4, 2, 6 67, 8delete 6 from heap and add to sorted array
15, 3, 4, 21, 5 6, 7, 8swap 1 and 5 as they are not in order in the heap
5, 1, 3, 4, 21, 4 6, 7, 8swap 1 and 4 as they are not in order in the heap
5, 4, 3, 1, 25, 2 6, 7, 8swap 5 and 2 in order to delete 5 from heap
2, 4, 3, 1, 5 56, 7, 8delete 5 from heap and add to sorted array
24, 3, 12, 4 5, 6, 7, 8swap 2 and 4 as they are not in order in the heap
4, 2, 3, 14, 1 5, 6, 7, 8swap 4 and 1 in order to delete 4 from heap
1, 2, 3, 4 45, 6, 7, 8delete 4 from heap and add to sorted array
1, 2, 31, 3 4, 5, 6, 7, 8swap 1 and 3 as they are not in order in the heap
3, 2, 13, 1 4, 5, 6, 7, 8swap 3 and 1 in order to delete 3 from heap
1, 2, 3 34, 5, 6, 7, 8delete 3 from heap and add to sorted array
121, 2 3, 4, 5, 6, 7, 8swap 1 and 2 as they are not in order in the heap
212, 1 3, 4, 5, 6, 7, 8swap 2 and 1 in order to delete 2 from heap
1, 2 23, 4, 5, 6, 7, 8delete 2 from heap and add to sorted array
1 12, 3, 4, 5, 6, 7, 8delete 1 from heap and add to sorted array
   1, 2, 3, 4, 5, 6, 7, 8completed




======================其他好文章==============================

http://www.cnblogs.com/dolphin0520/archive/2011/10/06/2199741.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值