c++ - 如何计算选择排序中的比较次数?

标签 c++ c selection-sort

如何计算selectionsort中的比较次数?

条款: 当您执行查找最大值的语句为“true”时 然后进行计数比较。

获取最大值的值保存在数组的第一个元素中,而不是随机的。

我尝试用C 可变计数位置变化 - 不起作用 新变量 'first' ,first=sort[MAX] 插入第一个 for 循环,- 不起作用

#include <stdio.h>

int main() {
    int sort[10000], i, n, MAX, temp, count;
    scanf("%d", &n);
    for (i = 0; i < n; i++) {
       scanf("%d", &sort[i]);
    }
    for (MAX = 0; MAX < n; MAX++)
        for (i = MAX + 1; i < n; i++) {
            if (sort[MAX] > sort[i]) {
                count++;
                temp = sort[MAX];
                sort[MAX] = sort[i]; 
                sort[i] = temp;
            }
        }

    printf("%d  ", count);
    return 0;
}

示例输入

10
0 7 1 6 7 7 6 6 5 4 

示例输出

17

编辑:新代码:

#include <stdio.h>
#define SWAP(x, y, temp) ( (temp)=(x), (x)=(y), (y)=(temp) )

int count = 0;

void selection_sort(int list[], int n) {
    int i, j, least, temp;

    for (i = 0; i < n - 1; i++) {
        least = i;

        for (j = i + 1; j < n; j++) {
            if (list[j] < list[least]) {
                least = j;
                count++;
            }
        }
        SWAP(list[i], list[least], temp);
    }
}

int main() {
    int list[10000], i, n;
    scanf("%d", &n);
    for (i = 0; i < n; i++) {
        scanf("%d", &list[i]);
    };
    selection_sort(list, n);

    printf("%d", count);
}

这个怎么样?为什么这段代码也没有动?

最佳答案

这段代码你算错了

     if(sort[MAX]>sort[i])  
     {
        count++;
         temp=sort[MAX];
         sort[MAX]=sort[i]; 
         sort[i]=temp;
     }

计算两个数字交换的次数。但你想计算比较,所以应该是这样的

     count++;
     if(sort[MAX]>sort[i])  // this is what we are counting
     {
         temp=sort[MAX];
         sort[MAX]=sort[i]; 
         sort[i]=temp;
     }

另一个问题是你没有给 count 初始值为零

int sort[10000],i,n,MAX,temp,count;

应该是

int sort[10000],i,n,MAX,temp,count = 0;

关于c++ - 如何计算选择排序中的比较次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55595267/

相关文章:

c++无法使选择排序正常工作

c++ - Windows 10 上的 GetTickCount 值

c++ - 在什么情况下,dynamic_cast<> 可能会失败?

c - 为什么整数类型的发送顺序是颠倒的?

c - linux中应用程序的自动打包

algorithm - 为什么我的选择排序比插入排序慢

c++ - 重访 vector 、指针、兔子和回收内存

c++ - 如何通过预处理器指令检查程序是否需要 Visual C++ 中的预编译头文件?

c - 保护内存中的凭据

java - 如何使用整数比较器实现选择排序?