《数据结构与算法分析——c语言描述》 练习6.11 答案
性能竟然相差两倍。buildheap复杂度是O(N),n次insert是O(NlogN)
#include"binheap.h" #include<stdlib.h> #include<stdio.h> #include<time.h> #define N 9999999 int RandInt(int i, int j) { int temp; temp = (int)(i + (1.0*rand() / RAND_MAX)*(j - i)); return temp; } void getRandomInt(int *A, int n) { for (int i = 0; i < n; i++) { A[i] = i + 1; } for (int i = 1; i < n; i++) { //std::swap(A[i], A[RandInt(0, i)]); int randAdrr = RandInt(0, i); int t = A[i]; A[i] = A[randAdrr]; A[randAdrr] = t; } } int randArr[N]; int proper[N]; int reverse[N]; int main() { getRandomInt(randArr, N); for (int i = 0; i < N; i++) proper[i] = i+1; for (int i = N - 1; i >= 0; i--) reverse[i] = i + 1; printf("rand:\n"); clock_t t1 = clock(); PriorityQueue h = initialize(N); for (int i = 0; i < N; i++) { insert(randArr[i], h); } clock_t t2 = clock(); printf("%f\n", ((double)t2 - t1) / CLOCKS_PER_SEC); destroy(h); t1 = clock(); h = buildHeap(randArr, N); t2 = clock(); printf("%f\n", ((double)t2 - t1) / CLOCKS_PER_SEC); destroy(h); printf("proper:\n"); t1 = clock(); h = initialize(N); for (int i = 0; i < N; i++) { insert(proper[i], h); } t2 = clock(); printf("%f\n", ((double)t2 - t1) / CLOCKS_PER_SEC); destroy(h); t1 = clock(); h = buildHeap(proper, N); t2 = clock(); printf("%f\n", ((double)t2 - t1) / CLOCKS_PER_SEC); destroy(h); printf("reverse:\n"); t1 = clock(); h = initialize(N); for (int i = 0; i < N; i++) { insert(reverse[i], h); } t2 = clock(); printf("%f\n", ((double)t2 - t1) / CLOCKS_PER_SEC); destroy(h); t1 = clock(); h = buildHeap(reverse, N); t2 = clock(); printf("%f\n", ((double)t2 - t1) / CLOCKS_PER_SEC); destroy(h); }