SWUST OJ 1015: C++ Implementation of Heap Sort Algorithm

topic description

Write a program heap sort algorithm. Sort in descending order, and the test data is an integer.

enter

The first line is the number of data elements to be sorted; the second line is the data elements to be sorted. (Hint: pile with small roots)

output

The result of a heap sort.

#include<bits/stdc++.h>
using namespace std;
int n, a[1000], i;
void f(int a[], int i, int n)
{
	int k=2*i;//k为双亲结点(i)的左孩子序号
	int top=a[i];//top储存双亲结点值 	
	while(k<=n){//循环终止条件
		if(k<n&&a[k]>a[k+1]) k++;//左右孩子中找较小的一个,记录他的序号
		if(top>a[k]){//双亲结点比较小值大则交换,否则退出循环。
			a[i]=a[k];
			i=k;
			k=2*i;
		}
		else break;
	}
	a[i]=top;
}
int main()
{
	cin>>n;
	for(i=1;i<=n;i++) cin >> a[i]; 
	for(i=n/2;i>=1;i--) f(a, i, n);//循环建堆
	for(i=1;i<=n;i++)cout << a[i] <<" ";
	
	return 0;
 } 

 

Guess you like

Origin blog.csdn.net/Ljy_Cxy/article/details/131465160