文件记录排序

    技术2022-05-11  20

    你现在有一个文件,文件中顺序存有N个记录,R1,R2,...,RN,这些记录不是有序的,但是你知道一个整数M,这些记录满足R1<R2<...<RM以及RM+1<RM+2<...RN.

    1,设计一个算法或编写一个程序,将文件中的记录排序为R1'<R2',<…<,RN',算法或程序读取文件的次数为O(N),不限内存使用,

    2, 设计一个算法或编写一个程序,将文件中的记录排序为 R1'<R2'<...<RN', 算法或程序读写文件的次数为 O(N) ,空间复杂度为 O(1) ( 亦即,你使用的内存大小和 M,N 均无关。 )   1.就是两个有序数组的合并了,时间复杂度确实是O(N),好说 2.第一个限制空间, or 内存不够时就是外部排序了.主要就是读写文件了. #include <stdio.h> #include <stdlib.h> #define MAX_LEN 10 #define M 5 #define N 10 int process_file1(int A[]) { FILE* fp1 = fopen("record_bak.txt","w"); int i = 0; int j = M; char line[MAX_LEN]; while(i<M && j<N) { if(A[i]<A[j]) { sprintf(line, "%d/n", A[i]); fwrite(line, 1, strlen(line), fp1); i++; } else { sprintf(line, "%d/n", A[j]); fwrite(line, 1, strlen(line), fp1); j++; } } if(i==M) { while(j<N) { sprintf(line, "%d/n", A[j]); fwrite(line, 1, strlen(line), fp1); j++; } } else if(j==N) { while(i<M) { sprintf(line, "%d/n", A[i]); fwrite(line, 1, strlen(line), fp1); i++; } } fclose(fp1); } int process_file2() { FILE* fp = NULL; FILE* fp1 = NULL; FILE* fp2 = NULL; char line1[MAX_LEN]; char line2[MAX_LEN]; int num1 = 0; int num2 = 0; int flag = 0; int i = 0; fp = fopen("record.txt","r"); fp1 = fopen("record_tmp1.txt","w"); fp2 = fopen("record_tmp2.txt","w"); while(fgets(line1, MAX_LEN, fp)) { printf("line is %s",line1); if(i<M) { printf("%d/n",fwrite(line1, 1, strlen(line1), fp1)); i++; } else { printf("%d/n",fwrite(line1, 1, strlen(line1), fp2)); i++; } } fclose(fp); fclose(fp1); fclose(fp2); fp = fopen("record.txt","w"); fp1 = fopen("record_tmp1.txt","r"); fp2 = fopen("record_tmp2.txt","r"); fgets(line1, MAX_LEN, fp1); fgets(line2, MAX_LEN, fp2); while(1) { num1 = atoi(line1); num2 = atoi(line2); if(num1 < num2) { fwrite(line1, 1, strlen(line1), fp); if(!fgets(line1, MAX_LEN, fp1)) { fwrite(line2, 1, strlen(line1), fp); flag = 1; break; } } else { fwrite(line2, 1, strlen(line2), fp); if(!fgets(line2, MAX_LEN, fp2)) { fwrite(line1, 1, strlen(line1), fp); flag = 2; break; } } } if(flag == 1) { while(fgets(line2, MAX_LEN, fp2)) fwrite(line2, 1, strlen(line2), fp); } else if(flag == 2) { while(fgets(line1, MAX_LEN, fp1)) fwrite(line1, 1, strlen(line2), fp); } fclose(fp); fclose(fp1); fclose(fp2); remove("record_tmp1.txt"); remove("record_tmp2.txt"); } int main(int argc, char *argv[]) { int A[N]; int i = 0; FILE* fp = NULL; char line[MAX_LEN]; fp = fopen("record.txt","r"); while(fgets(line, MAX_LEN, fp)) { A[i] = atoi(line); i++; } fclose(fp); process_file1(A); process_file2(A); system("PAUSE"); return 0; }

    最新回复(0)