堆排

这是文件操作进行堆排的,堆排函数写的是小顶堆,但是大顶堆的话,改一下函数部分就好,已加了注释:
#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值