【发布时间】:2013-12-03 05:49:19
【问题描述】:
我正在尝试编写一个程序来计算冒泡排序与插入排序的运行时间。它接受两个输入,元素的数量和元素的数量,并计算它们的运行时间。这是我到目前为止所拥有的,但它为两个分拣机同时打印。
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <time.h>
int bubblesort(int a[], int n);
int insertionsort(int a[], int n);
int main()
{
int s,temp,i,j,comparisons,a[20];
float function_time;
clock_t start;
clock_t end;
printf("Enter total numbers of elements: ");
scanf("%d",&s);
printf("Enter %d elements: ",s);
for(i=0;i<s;i++)
scanf("%d",&a[i]);
//Bubble sorting algorithm
for(i=s-2;i>=0;i--)
{
for(j=0;j<=i;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
for(i=0;i<s;i++)
a[i]= rand()%10000;
start = clock();
comparisons= bubblesort(a, s);
end = clock();
function_time = (float)(end)/(CLOCKS_PER_SEC); // Time in seconds
printf("\nTime for Bubble Sort is %f microseconds\n ", function_time);
// Insertion sorting algorithm
for(i=1;i<s;i++)
{
temp=a[i];
j=i-1;
while((temp<a[j])&&(j>=0))
{
a[j+1]=a[j];
j=j-1;
}
a[j+1]=temp;
}
for(i=0;i<s;i++)
a[i]= rand()%10000;
start = clock();
comparisons= insertionsort(a, s);
end = clock();
function_time = (float)(end)/(CLOCKS_PER_SEC); // Time in seconds
printf("\nTime for Insertion Sort is %f microseconds\n ", function_time);
return 0;
}
int bubblesort(int a[], int n)
{
bool swapped = false;
int temp=0, counter=0;
for (int j = n-1; j>0; j--)
{
swapped = false;
for (int k = 0; k<j; k++)
{
counter++;
if (a[k+1] < a[k])
{
temp= a[k];
a[k] = a[k+1];
a[k+1]= temp;
swapped = true;
}
}
if (!swapped)
break;
}
return counter;
}
int insertionsort(int a[], int n)
{
bool swapped = false;
int temp=0, counter=0;
for (int i=1; i<=n; i++)
{
for (int s=i; s>0; s--)
{
counter++;
if (a[s]<a[s-1])
{
temp=a[s-1];
a[s-1]=a[s];
a[s]=temp;
swapped = true;
}
}
if (!swapped)
break;
}
return counter;
}
【问题讨论】:
-
我认为你的代码是多余的。这两种类型的代码都重复了两次。为什么?
-
不确定如何更改或从哪里开始。
-
clock不是测量运行时间的合适方法。那是你的主要问题。分辨率太差了,在许多系统上它甚至不能像文档中描述的那样工作。 -
您需要使用
clock()比较大数据集——例如,尝试以 10k 为增量从 10k 到 50k。您还需要确保使用每种算法对相同的数据进行排序。通过您选择的任何机制创建数据,然后复制它;然后用冒泡排序对一个副本进行排序,另一个用插入排序对它们进行排序。 -
除了
clock是一个糟糕的计时方法选择之外,为了衡量诸如排序算法之类的性能,您需要对大量元素进行排序。考虑成百上千甚至数百万个元素,而不仅仅是用户可以输入的几件事。
标签: c sorting bubble-sort insertion-sort