如何使 C 语言的排序程序对于大型输入集更快

2024-03-02

对于非常大的输入文件数据,此排序代码会失败,因为它需要很长时间才能完成。

rewind(ptr);
j=0;
while(( fread(&temp,sizeof(temp),1,ptr)==1) &&( j!=lines-1)) //read object by object
{
  i=j+1;
  while(fread(&temp1,sizeof(temp),1,ptr)==1)  //read next object , to compare previous object with next object 
   {
       if(temp.key > temp1.key)   //compare key value of object 
           {
            temp2=temp; //if you don't want to change records and just want to change keys use three statements temp2.key =temp.key;
            temp=temp1;
            temp1=temp2;
            fseek(ptr,j*sizeof(temp),0);        //move stream to overwrite 
            fwrite(&temp,sizeof(temp),1,ptr);   //you can avoid above swap by changing &temp to &temp1 
            fseek(ptr,i*sizeof(temp),0);        //move stream to overwrite
            fwrite(&temp1,sizeof(temp),1,ptr);  //you can avoid above swap by changing &temp1 to &temp
           }
    i++; 
   }
  j++; 
  fseek(ptr,j*sizeof(temp),0);  
}

知道如何让这个 C 代码更快吗?也会使用qsort()(在 C 中预定义)要快得多,应该如何应用于上面的代码?


你问了这个问题根据文件中的键进行排序 https://stackoverflow.com/questions/18820288/sorting-based-on-key-from-a-file并得到了关于如何在内存中排序的各种答案。您添加了一个补充问题作为答案,然后创建了这个问题(这是正确的)。

Your code here is basically a disk-based bubble sort, with O(N2) complexity, and poor time performance because it is manipulating file buffers and disk. A bubble sort is a bad choice at the best of times — simple, yes, but slow.

加速排序程序的基本方法是:

  1. 如果可能的话,将所有数据读入内存,在内存中排序,然后将结果写出。
  2. 如果无法全部装入内存,请尽可能多地读入内存,对其进行排序,然后将排序后的数据写入临时文件。根据需要经常重复以对所有数据进行排序。然后将临时文件合并为一个文件。如果数据集确实是天文数字(或者内存确实很小),您可能必须创建中间合并文件。但如今,即使在 32 位计算机上,您也必须对数百 GB 的数据进行排序,这才成为一个问题。
  3. 确保选择好的排序算法。快速排序和适当的主元选择是非常好的。您也可以查找“introsort”。

您将在交叉引用问题(您的原始问题)的答案中找到示例内存排序代码。如果您选择编写自己的排序,则可以考虑是否将接口基于标准Cqsort()功能。如果你编写快速排序,你应该看看快速排序——选择枢轴 https://stackoverflow.com/questions/164163/quicksort-choosing-the-pivot/164183#164183其中答案有大量参考资料。

您将在答案中找到示例合并代码将多个已排序的文件合并为一个文件 https://stackoverflow.com/questions/18812266/merging-sorted-multiple-files-into-1-sorted-file。合并代码的性能优于系统sort程序处于合并模式,这很有趣,因为它不是高度抛光的代码(但它相当熟练)。

您可以查看中描述的外部排序程序软件工具 https://rads.stackoverflow.com/amzn/click/com/020103669X,尽管它有点深奥,因为它是用“RatFor”或 Rational Fortran 编写的。不过,该设计很容易转移到其他语言。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使 C 语言的排序程序对于大型输入集更快 的相关文章

随机推荐