当前位置:网站首页>Heap sort (principle plus code)

Heap sort (principle plus code)

2022-06-22 20:02:00 Just one word

Blog Garden others tutorial :
https://www.cnblogs.com/chengxiao/p/6129630.html

C The language code :

#include <stdio.h>

int count = 0;

void swap(int k[], int i, int j)
{
    
	int temp;

	temp = k[i];
	k[i] = k[j];
	k[j] = temp;
}

void HeapAdjust(int k[], int s, int n)
{
    
	int i, temp;

	temp = k[s];

	for( i=2*s; i <= n; i*=2 )
	{
    
		if( i < n && k[i] < k[i+1] )
		{
    
			i++;
		}

		if( temp >= k[i] )
		{
    
			break;
		}

		k[s] = k[i];
		s = i;
	}

	k[s] = temp;
}

void HeapSort(int k[], int n)
{
    
	int i;

	for( i=n/2; i > 0; i-- )
	{
    
		HeapAdjust(k, i, n);// From bottom to top , From left to right , Construct a large top heap from the initial unordered sequence 
	}

	for( i=n; i > 1; i-- )
	{
    
		swap(k, 1, i);// Swap the top of the heap with the last node 
		HeapAdjust(k, 1, i-1);// From the top down ( The root node is known to have changed ), Construct a large top pile from left to right 
	}
}

int main()
{
    
	int i, a[10] = {
    -1, 5, 2, 6, 0, 3, 9, 1, 7, 4};//a[0] As a vacancy , The root node is from a[1] Start , Easier to analyze code 

	HeapSort(a, 9);

	printf(" The result of sorting is :");
	for( i=1; i < 10; i++ )
	{
    
		printf("%d", a[i]);
	}
	printf("\n\n");

	return 0;
}
原网站

版权声明
本文为[Just one word]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206221828271901.html