我有一个任务,我需要一些帮助。我们要挑两个排序算法,C和效率比较两者。我写了下面的code,但我不知道,如果是比较合适的。我认为,掉期确定。我是新够本,如果你看到任何明显的缺陷,所以要温柔。
的#include< stdlib.h中>
#包括< time.h中>
#定义MAX 20
INT主要(无效)
{
//声明变量
INT I,X,Y,温度;
INT comparsioncounter = 0;
INT swapcounter = 0;
//我们的数组赋值。我没有使用随机数,所以我们可以比较两种方法
int数组[MAX] = {3,1,5,8,7,13,17,34,22,31,28,2,17,44,23,67,32,9,12,30};
//启动时钟时间执行时间
clock_t表示起点,终点;
启动=时钟();
的printf(排序的数组的\ n);
//打印排序的数组
对于(i = 0; I< MAX;我++){
的printf(%D,数组[I]);
}
的printf(\ N);
//我们的排序算法
为(X = 0,X< MAX; X ++){
对于(i = 0; I< MAX-1;我++){
//计数器来跟踪该比较多少次循环
comparsioncounter ++;
如果(数组[I]>阵[I + 1])
{
TEMP =数组[我]
数组[我] =阵列[i + 1];
阵列[1 + 1] =气温;
//计数器来跟踪该比较多少次循环
swapcounter ++;
}
}
}
//打印排序后的数组
的printf(\ nSorted阵列的\ n);
对于(i = 0; I< MAX;我++){
的printf(%D,数组[I]);
}
//打印出comparsions和掉期号码
的printf(comparsions的\ñ\ n已接收为%d \ N,comparsioncounter);
的printf(掉期的数量为%d,swapcounter);
结束=时钟();
//打印出执行时间
的printf(\ n时间采取以秒为单位:%.5lf \ N,((双)(结束 - 开始))/ CLOCKS_PER_SEC);
返回0;
}
解决方案
似乎是正确的。
做的另一种方式,以便在那里它可能更明显会写的比较和交换功能的数着柜台了。
是这样的:
静态无符号谱曲= 0,掉期= 0;
INT比较(INT L,INT读)
{
谱曲++;
返回(L> R);
}
无效掉期(INT * L,INT * R)
{
交换++;
INT T = * L;
* L = * R;
* R = T;
}
然后用它们来代替。
I have an assignment I need a little help with. We have to pick two sort algorithms in C and compare both on efficiency. I have written the following code but I am not sure if the comparisons are right. I think the swaps is OK. I am new enough to this so be gentle if you see any obvious faults.
#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;
}
解决方案
seems to be correct.
Another way of doing so where it's maybe more apparent would be writing a comparison and a swap function that count their counters up.
like this:
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;
}
and then use them instead.