我有一项任务,我需要一些帮助。我们必须在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;
}
答案 0 :(得分:1)
似乎是正确的。
另一种可能更明显的做法是写一个比较和交换功能,计算他们的计数器。
像这样: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;
}
然后再使用它们。