按字母顺序对名称进行排序:更有效的方法
Sorting names by alphabetical order: more efficient way
我正在开发一个应用程序,其中一个功能是 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
}
冒泡排序是 O(n^2)。你可以试试 Quicksort,它是 O(nlogn)。本质上,大多数排序算法都比您演示的冒泡排序更快。
有关最常见排序方法的列表、它们的动画以及它们的实现,请参阅以下页面:
我正在开发一个应用程序,其中一个功能是 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
}
冒泡排序是 O(n^2)。你可以试试 Quicksort,它是 O(nlogn)。本质上,大多数排序算法都比您演示的冒泡排序更快。
有关最常见排序方法的列表、它们的动画以及它们的实现,请参阅以下页面: