程序代码:
#include <stdio.h> #include <stdlib.h> #include <string.h> #define INIT_ROWS 100 #define INCREMENT 50 typedef struct { unsigned num1; unsigned num2; char name[9]; } DATA, * PDATA; void insertion_sort(void * data, unsigned num, unsigned size, int (* compare)(const void *, const void *)) { int i, j, k; void * temp = malloc(size); for(i = 1; i < num; i++) { for(j = 0; j < i; j++) if(compare(data + j * size, data + i * size) > 0) break; memcpy(temp, data + i * size, size); for(k = i; k > j; k--) memcpy(data + k * size, data + (k - 1) * size, size); memcpy(data + j * size, temp, size); } free(temp); } int compare1(const void * p1, const void * p2) { unsigned var1 = ((PDATA)(p1))->num1, var2 = ((PDATA)(p2))->num1; if(var1 == var2) return 0; if(var1 > var2) return 1; return -1; } int compare2(const void * p1, const void * p2) { unsigned var1 = ((PDATA)(p1))->num2, var2 = ((PDATA)(p2))->num2; if(var1 == var2) return 0; if(var1 > var2) return 1; return -1; } int main(void) { FILE * fp_in = NULL; FILE * fp_out = stdout; char in_file_name[128]; char out_file_name[128]; PDATA pdatas = (PDATA)malloc(sizeof(DATA) * INIT_ROWS); unsigned rows = 0; unsigned size = INIT_ROWS; unsigned i; printf("请输入需要排序的源文件名:"); fflush(stdout); scanf("%s", in_file_name); /* printf("请输入排序后存放的文件名:"); fflush(stdout); scanf("%s", out_file_name);*/ if((fp_in = fopen(in_file_name, "r")) == NULL) { printf("%s 打开失败,程序将结束!\n"); exit(1); } /* if((fp_out = fopen(out_file_name, "w")) == NULL) { printf("%s 打开失败,程序将结束!\n"); exit(1); }*/ while(fscanf(fp_in, "%u%u%s", &pdatas[rows].num1, &pdatas[rows].num2, pdatas[rows].name) != EOF) { if(++rows == size) { pdatas = realloc(pdatas, size += INCREMENT); if(pdatas == NULL) exit(1); // ....... } } insertion_sort(pdatas, rows, sizeof(DATA), compare2); insertion_sort(pdatas, rows, sizeof(DATA), compare1); for(i = 0; i < rows; i++) fprintf(fp_out, "%u %u %s\n", pdatas[i].num1, pdatas[i].num2, pdatas[i].name); fclose(fp_in); // fclose(fp_out); return 0; }
My life is brilliant