#include <iostream>
#include <time.h>
#include <assert.h>
#include <cstdlib>
using namespace std;
clock_t start, stop; // clock_t是clock()函数返回的变量类型
double duration;
// 冒泡排序
void sort1(int a[], int n) {
int i, j, temp;
int flag;
for (i = 0; i < n - 1; i++) {
flag = 0;
for (j = n - 1; j > i; j--) {
if (a[j - 1] > a[j]) {
temp = a[j - 1];
a[j - 1] = a[j];
a[j] = temp;
flag = 1;
}
}
if (flag == 0) break;
}
}
// 快速排序
int partition(int arr[], int left, int right) { // 找基准数 划分
int i = left + 1;
int j = right;
int temp = arr[left];
while (i <= j) {
while (arr[i] < temp) {
i++;
}
while (arr[j] > temp) {
j--;
}
if (i < j)
swap(arr[i++], arr[j--]);
else i++;
}
swap(arr[j], arr[left]);
return j;
}
void quick_sort(int arr[], int left, int right) {
if (left >= right)
return;
int j = partition(arr, left, right);
quick_sort(arr, left, j - 1);
quick_sort(arr, j + 1, right);
}
// 堆排序
void AdjustDown(int a[], size_t n, int root) {
size_t parent = root;
size_t child = parent * 2 + 1;
while (child < n) {
if (child + 1 < n && a[child + 1] > a[child]) {
++child;
}
if (a[child] > a[parent]) {
swap(a[child], a[parent]);
parent = child;
child = parent * 2 + 1;
} else {
break;
}
}
}
void HeapSort(int a[], size_t n) {
assert(a);
int parent = (n - 2) >> 1;
// 建堆
for (; parent >= 0; --parent) {
AdjustDown(a, n, parent);
}
for (int i = n - 1; i >= 0; --i) {
swap(a[0], a[i]);
AdjustDown(a, i, 0);
}
}
// 选择排序
void selectSort(int a[], int len) {
int minindex, temp;
for (int i = 0; i < len - 1; i++) {
minindex = i;
for (int j = i + 1; j < len; j++) {
if (a[j] < a[minindex])
minindex = j;
}
temp = a[i];
a[i] = a[minindex];
a[minindex] = temp;
}
}
void test_sorting_algorithms(int size) {
int* a = new int[size];
cout << "生成" << size << "个随机数" << endl << endl;
for (int i = 0; i < size; i++) {
a[i] = rand() % size;
}
int* temp = new int[size];
memcpy(temp, a, size * sizeof(int));
start = clock();
sort1(temp, size);
stop = clock();
duration = (double)(stop - start) / CLOCKS_PER_SEC;
cout << "冒泡排序运行时间是:" << duration << "秒" << endl << endl;
memcpy(temp, a, size * sizeof(int));
start = clock();
quick_sort(temp, 0, size - 1);
stop = clock();
duration = (double)(stop - start) / CLOCKS_PER_SEC;
cout << "快速排序运行时间是:" << duration << "秒" << endl << endl;
memcpy(temp, a, size * sizeof(int));
start = clock();
HeapSort(temp, size);
stop = clock();
duration = (double)(stop - start) / CLOCKS_PER_SEC;
cout << "堆排序运行时间是:" << duration << "秒" << endl << endl;
memcpy(temp, a, size * sizeof(int));
start = clock();
selectSort(temp, size);
stop = clock();
duration = (double)(stop - start) / CLOCKS_PER_SEC;
cout << "选择排序运行时间是:" << duration << "秒" << endl << endl;
delete[] a;
delete[] temp;
}
int main() {
srand(time(0));
test_sorting_algorithms(10);
test_sorting_algorithms(100);
test_sorting_algorithms(10000);
test_sorting_algorithms(1000000);
return 0;
}
为什么百万级的没有运行结果