1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| #include <time.h> #include <sys/time.h>
double get_time() { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec + tv.tv_usec / 1000000.0; }
void benchmark_sort_algorithm(void (*sort_func)(int[], int), const char *algorithm_name, int arr[], int n) { int *test_arr = (int*)malloc(n * sizeof(int)); memcpy(test_arr, arr, n * sizeof(int)); double start_time = get_time(); sort_func(test_arr, n); double end_time = get_time(); printf("%s: %.6f 秒\n", algorithm_name, end_time - start_time); bool is_sorted = true; for (int i = 1; i < n; i++) { if (test_arr[i] < test_arr[i - 1]) { is_sorted = false; break; } } printf("排序结果: %s\n", is_sorted ? "正确" : "错误"); free(test_arr); }
void run_sort_benchmarks(int n) { printf("=== 排序算法性能测试 (数组大小: %d) ===\n", n); int *original_arr = (int*)malloc(n * sizeof(int)); srand(time(NULL)); for (int i = 0; i < n; i++) { original_arr[i] = rand() % 10000; } benchmark_sort_algorithm(bubble_sort, "冒泡排序", original_arr, n); benchmark_sort_algorithm(selection_sort, "选择排序", original_arr, n); benchmark_sort_algorithm(insertion_sort, "插入排序", original_arr, n); benchmark_sort_algorithm(shell_sort, "希尔排序", original_arr, n); void quick_sort_wrapper(int arr[], int n) { quick_sort(arr, 0, n - 1); } void merge_sort_wrapper(int arr[], int n) { merge_sort(arr, 0, n - 1); } benchmark_sort_algorithm(quick_sort_wrapper, "快速排序", original_arr, n); benchmark_sort_algorithm(merge_sort_wrapper, "归并排序", original_arr, n); benchmark_sort_algorithm(heap_sort, "堆排序", original_arr, n); free(original_arr); }
|