【发布时间】:2015-01-04 15:27:12
【问题描述】:
我正在开发一个应用程序,其中一个函数是 sort_books 函数,它基本上必须按字母顺序对文件 fp 中的书籍名称进行排序,然后将书籍写入文件 fp2 并打印名称书籍按字母顺序进入控制台。
我的函数与冒泡排序算法完美配合,但要对 100000 本书进行排序大约需要 4 分钟,这实在是太长了。
有人知道我可以如何调整这段代码以提高效率和速度吗?
FILE *fp
FILE *fp2;
sort_books(){
struct book books[100000];
struct book b;
//open files
int i = 0;
while (!feof(fp)){
fread(&b,sizeof(b),1,fp);
if(feof(fp))
{
break;
}
books[i] = b;
i++;
}
//number of books in the file
int len = i;
//bubble sort;
int j = 0;
//Bubble sort: sorting algorithm
for(i=0; i<len; i++)
{
for(j=0; j<len-1; j++)
{
//If the first book should come after the next book in the array
if(strcmp(books[j].name, books[j+1].name) > 0)
{
//swap the books
struct book temp;
temp = books[j];
books[j] = books[j+1];
books[j+1] = temp;
}
}
}
//now write each book in the array "books" into the file one by one
int z;
for(z=0; z<len; z++)
{
fwrite(&books[z],sizeof(books[z]),1,fp2);
//test console
printf("Name: %s \n", books[z].name);
}
//close files
}
【问题讨论】:
-
尝试快速/合并排序?
-
几乎你发现的任何排序都比冒泡排序更有效。即使需要就地排序,单步遍历列表,找到最小值并将该值交换到第一个位置,然后从第二个元素开始重复,等等,它也更快,也更容易;这涉及移动的数据量(平均而言)仅为冒泡排序的一半。
-
不相关,但不要使用
while (1feof(fp)),它不会像你预期的那样工作,因为EOF标志直到在你尝试从其他地方读取之后才会设置文件的结尾。这意味着您将循环一次到多次迭代。相反,例如while (fread(...) == sizeof(b)) -
@Zombie :查看我的更新答案。如果这能回答您的问题,请告诉我。
标签: c sorting alphabetical