C 冒泡排序与插入排序运行时
我正试图编写一个程序来计算冒泡排序与插入排序的运行时间。它接受两个输入,元素数和元素数,并计算它们的运行时间。这是我到目前为止所拥有的,但它同时为两台分拣机打印C 冒泡排序与插入排序运行时,c,sorting,bubble-sort,insertion-sort,C,Sorting,Bubble Sort,Insertion Sort,我正试图编写一个程序来计算冒泡排序与插入排序的运行时间。它接受两个输入,元素数和元素数,并计算它们的运行时间。这是我到目前为止所拥有的,但它同时为两台分拣机打印 #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <time.h> int bubblesort(int a[], int n); int insertionsort(int a[], int n);
#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;
}
#包括
#包括
#包括
#包括
int bubblesort(int a[],int n);
int insertionsort(int a[],int n);
int main()
{
int s,temp,i,j,比较,a[20];
浮点数;
时钟没有启动;
时钟结束;
printf(“输入元素总数:”);
scanf(“%d”和“&s”);
printf(“输入%d个元素:”,s);
对于(i=0;i=0;i--)
{
对于(j=0;ja[j+1])
{
温度=a[j];
a[j]=a[j+1];
a[j+1]=温度;
}
}
}
对于(i=0;i首先,您计算排序时间的方法是错误的:
function_time = (float)(end)/(CLOCKS_PER_SEC);
应该是:
function_time = (float)(end-start)/(CLOCKS_PER_SEC);
第二,虽然冒泡排序和插入排序都有O(n平方)复杂度,但所花费的时间应该有所不同,它们不可能相同。如果问题仍然存在,您应该检查clock()函数的输出,它可能在您的系统中不起作用
编辑:我发现您的代码允许用户手动键入元素。因此我猜您的数组只能相对较小。排序较小的数组需要很少的时间,因此很难注意到差异。您应该让元素按代码随机分配,以便生成大数组进行分析。我认为您的代码是多余的。两种排序的代码都重复了两次。为什么?不确定如何更改或从何处开始。clock
不是测量运行时间的合适方法。这是您的主要问题。分辨率太低,在许多系统上甚至无法按文档所述工作。您需要使用clock()比较大数据集
-例如,以10k为增量尝试10k到50k。您还需要确保使用每个算法对相同的数据进行排序。使用您选择的任何机制创建数据,然后制作一个副本;然后使用冒泡排序对一个副本进行排序,另一个使用插入排序对其进行排序,并对其进行计时。此外,clock
是一个糟糕的选择在计时方法方面,为了衡量排序算法之类的性能,你需要对大量元素进行排序。考虑100个数千个甚至数百万个元素,而不仅仅是用户可以输入的一些东西。