三个排序算法,以时间为计算单位,对比它们的使用效率;为了准确对比,都使用了相同的数组;但是由于每次产生的随机数组都不同,导致排序遍历与交换的次数也不同;所以这里仅针对每一次的结果的对比,具体一定的随机性,但总的来说还是会趋近每个算法自身的时间复杂度。
其中的一个结果如下
selectSort:============
bubbleSort:=============
insertSort :==========
each sort used time: 12 13 10
代码如下:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define NUMBER 10000
double selectionSort(int [],int);
double bubbleSort(int [],int);
double quickSort(int [],int,int);
double insertSort(int [],int);
void showChart(int [],int);
void display(int [],int);
int main()
{
int num[NUMBER];
int num0[NUMBER];
int num1[NUMBER];
int num2[NUMBER];
int num3[NUMBER];
int timeList[3];
int randValue = 0;
int i,temp;
srand(time(NULL));
for(i=0;i<NUMBER;i++)
{
randValue=1+(int)rand()%100;
num[i]=randValue;
num0[i]=randValue;
num1[i]=randValue;
num2[i]=randValue;
num3[i]=randValue;
}
timeList[0]=(int)(selectionSort(num0,NUMBER)*20);
timeList[1]=(int)(bubbleSort(num1,NUMBER)*20);
timeList[2]=(int)(insertSort(num2,NUMBER)*20);
showChart(timeList,3);
printf("each sort used time:\t");
for(i=0;i<3;i++){
printf("%d\t",timeList[i]);
}
printf("\n");
return 0;
}
double selectionSort(int num[],int count)
{
int i,j,min,minIndex,temp;
clock_t begin, end;
double cost;
begin = clock();
for(i = 0;i< (count-1);i++)
{
min=num[i];
minIndex=i;
for(j=i+1;j<count;j++)
{
if(num[j]<min)
{
min=num[j];
minIndex=j;
}
}
if(min<num[i])
{
temp=num[i];
num[i]=min;
num[minIndex]=temp;
}
}
end = clock();
cost = (double)(end - begin) / CLOCKS_PER_SEC;
//display(num,count);
return cost;
}
double bubbleSort(int num[],int count)
{
int i,j,temp;
clock_t begin, end;
double cost;
begin = clock();
for(i = 0;i < (count-1);i++)
{
for(j = i+1;j < count;j++){
if(num[i]>num[j]){
temp=num[j];
num[j]=num[i];
num[i]=temp;
}
}
}
end = clock();
cost = (double)(end - begin) / CLOCKS_PER_SEC;
//display(num,count);
return cost;
}
double insertSort(int num[],int count)
{
clock_t begin, end;
double cost;
int i,j,temp;
begin = clock();
for(i = 1;i < count;i++)
{
temp=num[i];
j=i-1;
while((j>=0)&&(temp<num[j]))
{
num[j+1]=num[j];
j--;
}
num[j+1]=temp;
}
end = clock();
cost = (double)(end - begin) / CLOCKS_PER_SEC;
return cost;
}
void showChart(int num[],int count)
{
int i,j;
for(i=0;i<count;i++)
{
if(i==0)
printf("selectSort:");
if(i==1)
printf("bubbleSort:");
if(i==2)
printf("insertSort:");
for(j=0;j<num[i];j++)
{
printf("=");
}
printf("\n");
}
}
void display(int num[],int count)
{
int i;
for(i=0;i<count;i++)
{
printf("%d\t",num[i]);
}
}
代码写得没有什么可观赏价值,有什么不足之处欢迎指出。