這裡我們實做兩種交換方式
1. 將陣列宣告在 stack,交換時必須搬移多個元素
2. 用指標指向陣列,交換時只改變指標指向的位址
#include <algorithm>
#include <iostream>
#include <ctime>
using namespace std;
int cmp1(const void *_a, const void *_b)
{
const int *a = (const int *)_a,
*b = (const int *)_b;
return a[1] > b[1];
}
int cmp2(const void *_a, const void *_b)
{
const int *a = *(const int * const *)_a,
*b = *(const int * const *)_b;
return a[1] > b[1];
}
int main()
{
clock_t start, end;
constexpr int len = 10000;
int arr1[10][len];
for(int i = 0; i<10; i+=1)
for(int j = 0; j<len; j+=1)
arr1[i][j] = len-j;
start = clock();
qsort(arr1, 10, sizeof(arr1[0]), cmp1);
end = clock();
cout << "time: " << end - start << endl;
int **arr2 = new int*[10];
for(int i = 0; i<10; i+=1){
arr2[i] = new int[len];
for(int j = 0; j<len; j+=1)
arr2[i][j] = len-j;
}
start = clock();
qsort(arr2, 10, sizeof(arr2[0]), cmp2);
end = clock();
cout << "time: " << end - start << endl;
}
留言列表