这是文件操作进行堆排的,堆排函数写的是小顶堆,但是大顶堆的话,改一下函数部分就好,已加了注释:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
const int N = 100;
void HeapAdjust(int* a, int s, int m)
{
int rc, j;
rc = a[s];
for(j = 2*s; j <= m; j *= 2)
{
if(j < m && a[j] < a[j+1]) //大顶堆:a[j] > a[j+1]
++j;
if(rc > a[j]) // 大顶堆:rc < a[j]
break;
a[s] = a[j];
s = j;
}
a[s] = rc;
}
void HeapSort(int* a, int n)
{
int i, temp;
for (i = n/2; i > 0; --i)
HeapAdjust(a, i, n);
for(i = n; i > 1; --i)
{
temp = a[1];
a[1] = a[i];
a[i] = temp;
HeapAdjust(a, 1, i-1);
}
}
int main()
{
time_t t;
int n, a[N+1];
srand((unsigned)time(&t));
for (int i = 1; i <= N; i++)
{
n = rand()%100;
a[i] = n;
}
printf("Before sorting(data in file):\n");
for (int i = 1; i <= N; i++)
printf("%d\t", a[i]);
FILE *fp;
fp = fopen("exp5.txt", "wb");
if(fp == NULL)
{
printf("Error in open your file\n");
exit(0);
}
fwrite(a, sizeof(int), N+1, fp);
fclose(fp);
fp = fopen("exp5.txt", "rb");
if(fp == NULL)
{
printf("Error in open your file\n");
exit(0);
}
int b[N+1];
fread(b, sizeof(int), N+1, fp);
HeapSort(b, N);
printf("\nAfter sorting:\n");
for (int i = 1; i <= N; i++)
printf("%d\t", b[i]);
system("pause");
return 0;
}