c - 选择排序计数比较

标签 c selection-sort

我有一个带有选择排序的程序,它可以生成随机数并按升序和降序排序。问题在于比较的计数。它给出了 10 0000 个数字之前的正确数字,但是当我生成 100k 个数字时,它返回的值比公式中的值错误。 这是我的选择排序代码。

void select (int n, float *pole2,int *compare,int *move,char decide)
{
    *compare=0; // number of comparisons
    *move=0;

int i; 
     for (i = 0; i < n - 1; i++)
     {                              
         int j, poz_min;
         float temp,min;
         min = pole2[i];
         poz_min = i;//
         for (j = i+1; j < n; j++)
         {  
                *compare+=1;
                 if (pole2[j] < min)
                 {  
                    min = pole2[j];
                    *move+=1;
                    poz_min=j;
                 }  
         }
         temp = pole2[i];
         pole2[i] = pole2[poz_min];
         pole2[poz_min] = temp;
         *move+=3;
     }


// Writing to a binary file     

FILE *fw;
    fw = fopen("Select_SORT.DAT", "wb+");
int z;
for(z = 0; z < n; z++)
    {
        fwrite(&pole2[z], sizeof(pole2[z]), 1, fw);
    }
 fclose(fw);


 fseek(fw, 0, SEEK_SET);


}

最佳答案

那是因为对于 100K 实际上有 10^10 比较。您系统上的 int 无法容纳它。为了安全起见,请尝试使用long long。还要将您得到的结果与 INT_MAX 进行比较。你就会明白了。

对于n个元素,有O(n^2)(准确地说是n*(n-1)/2)比较如果是选择排序。

关于c - 选择排序计数比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47959835/

相关文章:

algorithm - 选择或插入排序在学术环境之外有用吗?

c - 如何将 __m128d simd vector 的内容存储为 double 而不将其作为 union 访问?

命令行参数不返回正确的总数

c - 在 C 中将预定义变量作为指针传递

c - 编写一个 C 程序,从附带的数据文件中读取整数,并使用插入排序将排序后的数据存储到数组中

arrays - 调用函数对 n 个数字的数组进行排序时出错

java - 为什么在一般情况下,冒泡排序比选择排序表现更好

c - 用c编写的listSort函数工作错误

c - 在 C 中使用 scanf 进行模式匹配

c - Swift to C 桥接 : String to UnsafePointer<Int8>? 没有自动桥接?