帮忙对比一下看看下面两个快排效率如何~
某同学弄了两个快排代码,看上去差不多,就是选取的基数不同,运行时间也有些差别~先上代码~
程序代码:
#include<stdio.h>
//int a[101],n;
//Quicksort w/o a separate compare function :)
void quicksort(int A[], int lo, int hi) {
int i, j, pivot, temp;
if(lo == hi) return;
i=lo;
j=hi;
pivot= A[(lo+hi)/2];
/* Split the array into two parts */
do {
while (A[i] < pivot) i++;
while (A[j] > pivot) j--;
if (i<=j) {
temp= A[i];
A[i]= A[j];
A[j]=temp;
i++;
j--;
}
} while (i<=j);
if (lo < j) quicksort(A, lo, j);
if (i < hi) quicksort(A, i, hi);
}
int main()
{
int i,j,t;
//读入数据
//scanf("%d",&n);
// for(i=1;i<=n;i++)
// scanf("%d",&a[i]);
int a[10]={1,3,4,8,2,9,7,5,0,6};
quicksort(a,0,10); //快速排序调用
//输出排序后的结果
for(i=0;i<10;i++)
printf("%d ",a[i]);
// getchar();
//getchar();
return 0;
}
第二个是~
程序代码:
#include <stdio.h>
//int a[101],n;//定义全局变量,这两个变量需要在子函数中使用
void quicksort(int a[],int left,int right)
{
int i,j,t,temp;
if(left>right)
return;
temp=a[left]; //temp中存的就是基准数
i=left;
j=right;
while(i!=j)
{
//顺序很重要,要先从右边开始找
while(a[j]>=temp && i<j)
j--;
//再找右边的
while(a[i]<=temp && i<j)
i++;
//交换两个数在数组中的位置
if(i<j)
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
//最终将基准数归位
a[left]=a[j];
a[j]=temp;
quicksort(a,left,i-1);//继续处理左边的,这里是一个递归的过程
quicksort(a,i+1,right);//继续处理右边的 ,这里是一个递归的过程
}
int main()
{
int i,j,t;
//读入数据
//scanf("%d",&n);
//for(i=1;i<=n;i++)
// scanf("%d",&a[i]);
int a[10]={1,3,4,8,2,9,7,5,0,6};
quicksort(a,0,10); //快速排序调用
//输出排序后的结果
for(i=0;i<10;i++)
printf("%d ",a[i]);
//getchar();getchar();
return 0;
}
第一个代码比较快一点,是不是和基数选取的问题有关呢?
帮忙看看就可以了
~



