gpt4 book ai didi

计算简单排序程序中的比较和交换

转载 作者:行者123 更新时间:2023-11-30 19:17:18 24 4
gpt4 key购买 nike

我有一项作业需要一些帮助。我们必须选择两种 C 语言排序算法并比较它们的效率。我编写了以下代码,但我不确定比较是否正确。我觉得互换还是可以的我对此还很陌生,所以如果您发现任何明显的错误,请保持温和。

#include <stdlib.h>
#include <time.h>
#define MAX 20


int main(void)
{
//Declare variables
int i,x,y,temp;
int comparsioncounter=0;
int swapcounter=0;
//Assign values to our array. I didn’t use random numbers so we could compare the two methods
int array[MAX]= {3,1,5,8,7,13,17,34,22,31,28,2,17,44,23,67,32,9,12,30};

//start clock to time execution time
clock_t start, end;
start = clock();
printf("Unsorted array\n");
//print unsorted array
for(i=0; i<MAX;i++){
printf("%d ",array[i]);
}
printf("\n");
//Our sort algorithm
for (x=0; x<MAX; x++){
for(i=0;i<MAX-1;i++){
//counter to keep track of how many times the comparison loops
comparsioncounter++;
if(array[i]>array[i+1])
{
temp=array[i];
array[i]=array[i+1];
array[i+1]=temp;
//Counter to keep track of how many times the comparison loops
swapcounter++;
}
}

}
//print sorted array
printf("\nSorted array\n");
for(i=0; i<MAX;i++){
printf("%d ",array[i]);

}
//Print out number of comparsions and swaps
printf("\n\nNumber of comparsions is %d\n", comparsioncounter);
printf("Number of swaps is %d", swapcounter);
end = clock();
//print out execution time
printf("\nTime taken in seconds: %.5lf\n", ((double)(end - start))/CLOCKS_PER_SEC);
return 0;
}

最佳答案

看来是正确的。

另一种可能更明显的方法是编写一个比较和交换函数来对计数器进行计数。

像这样:

static unsigned comps = 0, swaps = 0;

int compare(int l, int r)
{
comps++;
return (l > r);
}

void swap(int *l, int *r)
{
swaps++;
int t = *l;
*l = *r;
*r = t;
}

然后使用它们。

关于计算简单排序程序中的比较和交换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28366522/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com