中大-复试-2011-编程题二

本文介绍了一种使用C语言实现的文本排序算法,通过读取文本文件中的数据,对其进行排序,并将结果输出到另一个文件中。具体操作包括创建数据文件、快速排序算法实现、读取文件数据、排序并输出排序后的结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:从in.txt输入数据,排序,在输出到out.txt,每行数据开始第一个数是元素的个数

输入:14 3 35 4 72 19 8 -3 29 -2 18 -25 4 72 100

输出:-25 -3 -2 3 4 4 8 18 19 29 35 72 72 100 

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void creatNewFile()
{
    FILE *file;
    //char t[100]="3 35 4 72 19 8 -3 29 -2 18 -25 4 72 100";
    char t[100]="14 3 35 4 72 19 8 -3 29 -2 18 -25 4 72 100";
    if ((file = fopen("in.txt", "w+")) == NULL) {
        printf("can't open the file!");
        exit(0);
    }
    fputs(t, file);
    fclose(file);
}

void quickSort(int arr[], int s, int e)
{
    if (s<e) {
        int i=s, j=e, t=arr[s];
        while (i<j) {
            while (i<j & arr[j]>=t) {
                j--;
            }
            if (i<j) {
                arr[i] = arr[j];
            }
            while (i<j && arr[i]<=t) {
                i++;
            }
            if (i<j) {
                arr[j] = arr[i];
            }
        }
        arr[i] = t;
        quickSort(arr, s, i-1);
        quickSort(arr, i+1, e);
    }
}

int main(int argc, const char * argv[])
{
    creatNewFile();//创建数据文件
    FILE *in, *out;
    char ch;
    int i=0, c[100], j;
    if ((in = fopen("in.txt", "r")) == NULL) {
        printf("can't open the file in!");
        exit(0);
    }
    fscanf(in, "%d", &j);
    while (j--) {
        fscanf(in, "%d", &c[i]);
        i++;
    }
    /*
    while ((fscanf(in, "%d", &c[i])) != EOF) {
        i++;
    }*/
    fclose(in);
    quickSort(c, 0, i-1);
    if ((out = fopen("out.txt", "w+")) == NULL) {
        printf("can't open the file out!");
        exit(0);
    }
    for (j=0; j<i; j++) {
        fprintf(out, "%d", c[j]);
        fputc(' ', out);
    }
    fclose(out);
    /*测试
    if ((out = fopen("out.txt", "r")) == NULL) {
        printf("can't open the file out!");
        exit(0);
    }

    while ((ch = fgetc(out)) != EOF) {
        printf("%c", ch);
        
    }
    fclose(out);
    */
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值