您的位置:首页 > 编程语言 > C语言/C++

堆排序(C++)

2015-01-09 17:19 239 查看
建立一个小顶堆;

建立时保证左子树右子树大于根节点;

去掉堆顶;

然后把最后一项放在堆顶,然后再调整保证左子树右子树大于根节点;

再去掉堆顶;

以此类推;

#include <iostream>
using namespace std;

int main()
{
int n;
cout << "请输入数组长度:" << endl;
cin >> n;
int *NUM = new int
;
cout << "请输入" << n << "个元素" << endl;

for (int i = 0; i < n; i++)
{
int j = i, temp;
cin >> NUM[i];
while (j > 0)
{
if (NUM[((j - 1) / 2)] > NUM[j])
{
temp = NUM[(j - 1) / 2];
NUM[(j - 1) / 2] = NUM[j];
NUM[j] = temp;
}
j = (j - 1) / 2;
}
}
while (n > 0)
{
int temp, tt;
cout << NUM[0] << endl;
NUM[0] = NUM[n - 1];
n--;
temp = 0;
while (((2 * temp + 1) < n) && ((2 * temp + 1) < n))
{
if ((NUM[temp] <= NUM[temp * 2 + 1]) && (NUM[temp] <= NUM[temp * 2 + 2]))
{
break;
}
else
{
if (NUM[temp * 2 + 1] < NUM[temp * 2 + 2])
{
tt = NUM[temp];
NUM[temp] = NUM[temp * 2 + 1];
NUM[temp * 2 + 1] = tt;
temp = temp * 2 + 1;
}
else
{
tt = NUM[temp];
NUM[temp] = NUM[temp * 2 + 2];
NUM[temp * 2 + 2] = tt;
temp = temp * 2 + 2;
}
}
}
}
delete[]NUM;
return 0;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: