#include <stdio.h> #include <stdlib.h>
#define MAX_NUM 20
void print_array(FILE* fp) { int num; int i ; for(i=0;i<MAX_NUM;i++) { fscanf( fp, "%d\n", &num); if((i+1)%5 == 0) printf("%d\n", num); else printf("%d\t", num); } }
void externalsort(FILE* fp, int M) { int i = 0; int flag = 0; int A[2]; FILE* fp_tmp1 = fopen("tmp1.txt","wb+"); FILE* fp_tmp2 = fopen("tmp2.txt","wb+"); for(i=1;i<=M;i++) { if(fscanf( fp, "%d\n", &A[0])!=EOF) { fprintf( fp_tmp1,"%d\n", A[0]); } } for(i=M+1;i<=MAX_NUM;i++) { if(fscanf( fp, "%d\n", &A[0])!=EOF) { fprintf( fp_tmp2,"%d\n", A[0]); } } rewind(fp_tmp1); rewind(fp_tmp2); fscanf( fp_tmp1, "%d\n", &A[0]); fscanf( fp_tmp2, "%d\n", &A[1]); rewind(fp); for(i=1;i<MAX_NUM+1;i++) { if(A[0]<=A[1]) { fprintf(fp, "%d\n", A[0]); if(fscanf( fp_tmp1, "%d\n", &A[0]) == EOF) { flag = 1; break; } } else { fprintf(fp, "%d\n", A[1]); if(fscanf( fp_tmp2, "%d\n", &A[1]) == EOF) { flag = 2; break; } } } while(i++<MAX_NUM+1) { if(flag == 1) { fprintf(fp, "%d\n", A[1]); while(fscanf( fp_tmp2, "%d\n", &A[1]) != EOF) fprintf(fp, "%d\n", A[1]); } else { fprintf(fp, "%d\n", A[0]); while(fscanf( fp_tmp1, "%d\n", &A[0]) != EOF) fprintf(fp, "%d\n", A[0]); } } remove("tmp1.txt"); remove("tmp2.txt"); }
int main(int argc, char *argv[]) { int i; int num; FILE* fp = NULL; srand((unsigned int)time(NULL)); fp = fopen("original.txt","wb+"); for(i=1;i<=10;i++) { num = 2*i-1; fprintf( fp, "%d\n", num); } for(i=1;i<=10;i++) { num = 2*i; fprintf( fp, "%d\n", num); } rewind(fp); printf("the original array is:\n"); print_array(fp); rewind(fp); externalsort(fp, MAX_NUM/2); printf("after external sort the array is:\n"); rewind(fp); print_array(fp); system("PAUSE"); return 0; }
|