<title>The implementation of the sort heap and the use of heaps to sort</title> The implementation of the sort heap and the use of heaps to sort table of Contents
- A few basic definitions
- Heapy: Adjusting the heap
- Build: Build a heap
- Insert: Inserting a new element
- Removetop: Remove the top of the heap
- Now use the heap to sort, just removetop every time.
Heaps are the most interesting data structures, and it's easy to write a heap when you see the introduction to algorithms. The process of implementing the heap always let us YY together the code and the data are our own control
For a more convenient implementation of the heap, we usually count from 1, not 0, and of course the number of No. 0 elements that can be used to store the heap. For convenience, or to use a variable to save the heap size, the following starts YY
A few basic definitions
int a[100] = {0, 4, 187, 109, 89, 13, 70, 29, 81, 168, 195};int Len= 10;void Swap(int I,int J) {int T= A[i]; A[i] = A[j]; A[J] = t; }int par(int I) {returnI/2;}int Left(int I) {returni*2;}int Right(int I) {returnI*2 + 1;}
Heapy: Adjusting the heap
void heapy(int I) {int L= Left (i);int R= Right (i);int Max= i;// Suppose I is the largest // find out whether the largest number is the left node of I or I, or the right node of I if(l <= len && a[l] > A[max]) {max = L; }if(R <= Len && A[r] > A[max]) {max = R; }if(I! = max) {// I not max, start adjustingSwap (I, max); Heapy (max);// Adjust yourself recursively}}
Build: Build a heap
void Build_heap () {for (inti cannot start from 1 to LEN/2 heapy (i); }} void Show () { for (inti = 1; I <= len; i++) { printf ("%d", A[i]); } printf ("\ n");} int Main (void) { build_heap (); Show (); return 0;}
Insert: Inserting a new element
void Insert (intx) { len++; A[len] = x; int i = len; int p = par (i); while (A[i] > A[p]) { swap (I, p); i = P; p = par (i); }} int Main (void) { build_heap (); Show (); Insert (175); Show (); return 0;}
Removetop: Remove the top of the heap
int Remove_top() {swap (1, Len);// Len is the last one . int x= A[len]; len--;// Note that the length-1, then adjustHeapy (1);// re-sizing the heap returnx;}int Main(void) {build_heap (); Show (); Insert (175); Show ();int ret= Remove_top (); Show (); printf"\n%d\n", ret);return0;}
Now use the heap to sort, just removetop every time.
void Heap_sort () { intnum = len; Save Len First, because Len waits for a 1 for (inti = 1; I <= num; i++) { printf ( "%d", Remove_top ()); } printf ("\ n");} int Main (void) { build_heap (); Show (); Heap_sort (); return 0;}
The implementation of the sort heap and the use of heaps to sort