您的位置:首页 > 其它

堆排序 (Heapsort)

2013-09-26 15:29 351 查看
原文: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
Heapnewly added elementswap 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.
Heapswap elementsdelete elementsorted arraydetails
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: