#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<ctime>
using namespace std;
#define MAXSIZE 10
const int n = MAXSIZE;
int num[n+1];
int number;
void init()
{
number = n;
for (int i = 1; i <=n; i++) num[i] = rand() % 100;//产生MAXSIZE(10)个数据 数据范围为0~~~99;
}
void output()
{
for (int i = 1; i <= n; i++)
{
printf("%d ", num[i]);
//if (i % 10 == 9) printf("\n");
}
printf("\n");
}
;
// order by asc
// 构造最大堆
// 堆排序 存储位置为 1...........n
void adjust(int num[],int root,int n)
{
//int temp;
int child;
int rootkey = num[root];
//temp = num[root];
child = root;
while (child*2 <= n)
{
child *= 2;
if (child < n && num[child] < num[child + 1]) child++;
if (rootkey < num[child])
{
num[child / 2] = num[child];
}
else break;
}
num[child] = rootkey;
}
void heap_sort(int num[],int number)
{
int i, j;
for (i = number / 2; i > 0; i--)
adjust(num, i, number);
for (i = number; i > 0; )
{
swap(num[i--], num[1]);
adjust(num, 1, i);
}
}
/
void check()
{
int flag = 1;
for (int i = 1; i <=n - 1; i++)
{
if (num[i] <= num[i + 1]) continue;
else { flag = 0; break; }
}
if (flag) printf("correct sort\n");
else printf("something wrong!\n");
}
int main()
{
srand((unsigned)time(NULL));
init();
output();
//
printf("堆排序:\n");
heap_sort(num, number);
;
/
output();
check();
return 0;
}
34. 堆排序
最新推荐文章于 2019-08-15 14:59:56 发布