In simple sorting, no comparison results are saved. During the next comparison, many comparisons have been done in the previous one, so the comparison times are large. If you can save the comparison results at the same time of each comparison, the overall sorting efficiency will be very high, and heap sorting is an improvement.
A heap is a complete binary tree with the following properties: the value of each node is greater than or equal to the value of the left and right child nodes; or each node is smaller than or equal to the value of its left and right child nodes.
Heap sorting ideas:
1. initialize the heap. Store the keywords to be sorted in the array r [1... in n], r is regarded as a Complete Binary Tree in sequence representation. Each node represents a record. The left child of any node r [I] is r [2i]. the right child is r [2i + 1], and the parent is r [I/2];
2. Create a heap. Adjust the binary tree so that the key values of each node meet the following conditions: r [I]. key> = r [2i]. key and r [I]. key> = r [2i + 1]. key; construct a large top heap.
3. Rebuild the heap. The maximum value of the entire sequence is the root node of the heap top. Removing it is actually to exchange it with the end element of the heap array. At this time, the end element is the maximum value ), then, the remainder n-1 sequences are re-constructed into a large top heap to obtain the next small value of n elements. After repeated execution, an ordered sequence can be obtained.
# Include <stdio. h> # include <stdlib. h> void swap (int arr [], int I, int j) {int temp; temp = arr [I]; arr [I] = arr [j]; arr [j] = temp;} void HeapAdjust (int arr [], int s, int m) {int temp; int j; temp = arr [s]; for (j = 2 * s + 1; j <m; j * = 2) {if (j <M-1 & arr [j] <arr [j + 1]) + + j;/* j is the following table of records with a large keyword */if (temp> = arr [j]) break; arr [s] = arr [j]; s = j;} arr [s] = temp;} void HeapSort (int arr [], int n) {int I; for (I = n/2-1; i> 0; I --) // construct the HeapAdjust (arr, I, n); for (I = n-1; I> 0; I --) {swap (arr, 0, I); HeapAdjust (arr, 0, I-1) ;}} void print (int arr [], int n) {int I; for (I = 0; I <n; I ++) {printf ("% d", arr [I]);} printf ("\ n");} int main () {int arr [] = {9, 1, 5, 8, 3, 7, 4, 6, 2}; int n = sizeof (arr) /sizeof (arr [0]); printf ("Before sorting: \ n"); print (arr, n); HeapSort (arr, n); printf ("after sorting: \ n "); print (arr, n); system (" pause "); return 0 ;}
This article is from "Li Haichuan" blog, please be sure to keep this source http://lihaichuan.blog.51cto.com/498079/1282235