-1
我有一个任务,我需要一点帮助。我们必须在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;
}
对于非常小的一组输入,在纸*上进行计算*,然后与您在程序中获得的结果进行比较。如果两者都相同,那么你可能是正确的,否则有什么问题。 – 2015-02-06 13:12:44
'x <20; .. i <19':20 * 19 ='380' – BLUEPIXY 2015-02-06 13:13:56
如果我将数组缩小到4的大小。掉换计数正确,但比较返回16.我不认为这是正确的 – niallo27 2015-02-06 13:14:03