我想要比较sort和归并对同一个数组排序的用时长短,觉得应该sort()比自己写的快,但实验结果却相反。1000000左右的排序似乎其他人测试的sort用时大概在0.15左右,但我运行的却是0.5以上。是代码有问题还是运行出了问题呢?
#include <iostream>
#include<algorithm>
#include <random>
#include<ctime>
using namespace std;
template<class T1>
void Merge(T1 a[], int l, int m, int r, T1 c[])
{
//已知a[l]<=…<=a[m];a[m+1]<=a[r]
//归并到c[l]~c[r],并复制到a[l]~a[r]
int i = l;
int j = m + 1;
int k = l;
while (i <= m && j <= r)
{
if (a[i] < a[j])
{
c[k] = a[i];
i++;
k++;
}
else
{
c[k++] = a[j++];
}
}
while (i <= m)
{
c[k++] = a[i++];
}
while (j <= r)
{
c[k++] = a[j++];
}
k = l;
while (k <= r)
{
a[k] = c[k];
k++;
}
}
template<class T11>
void MergeSort(T11 a[], int l, int r, T11 c[])
{
//a[l]~a[r]进行排序
if (l >= r)
{
return;
}
int m = (l + r) / 2;
MergeSort(a, l, m, c);
MergeSort(a, m + 1, r, c);
Merge(a, l, m, r, c);
}
void main()
{
int n;
n = 1000000;
float* a = new float[n];
float* b = new float[n];
float* c = new float[n];
for (int i = 0; i < n; i++)
{
//cout << "随机生成a[" << i << "]的值为";
a[i] = rand() % 100000000;
b[i] = a[i];
//cout << a[i] << endl;
}
clock_t start1, end1, start2, end2;
start1 = clock();
MergeSort(a, 0, 999999, c);
end1 = clock();
cout << start1 << " " << end1;
cout << "归并排序用时为" <<(double)( end1 - start1)/CLOCKS_PER_SEC << endl;
start2 = clock();
sort(b, b + 1000000);
end2 = clock();
cout << start2 << " " << end2;;
cout << "sort函数用时为" << (double)(end2 - start2) /CLOCKS_PER_SEC << endl;
for (int i = 0; i < 1000000; i++)
{
if (a[i] != b[i])
cout << "error!" << endl;
}
delete[] a;
delete[] b;
delete[] c;
}
代码大概就是这样,通过前两个函数进行归并排序,并用了模板类。之后用rand()随机产生随机数。a数组和b数组完全一样。对a数组进行归并排序,对b数组进行sort排序。c数组是为了辅助归并排序的数组。之后用clock()进行计时,输出得到用时。最后那个循环是为了检测是否归并排序出错。
运行结果及报错内容
我的运行结果大概是这样的,归并0.15左右,而sort0.5以上。
我的解答思路和尝试过的方法
我尝试用不同的函数获取用时,timeGetTime(),GetTickCourt()。但结果都是这样的
我想要达到的结果
我想要得到sort()和归并到底谁更快,以及为什么我的实验结果sort()运行有0.5s以上这么久?
求高人指点!