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

来源:互联网 发布:君麻吕实力 知乎 编辑:程序博客网 时间:2024/06/03 03:08

题目:从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;}


0 0
原创粉丝点击