利用随机数生成函数,产生待排序序列,序列长度可任意指定 设计CSort类 ,完成冒泡排序、选择排序和插入排序三种排序方法设计 调用系统函数,实现算法运行时间统计C++
时间: 2024-06-03 14:08:52 浏览: 125
#include <iostream>
#include <ctime>
using namespace std;
class CSort {
private:
int* arr; // 待排序序列
int len; // 序列长度
public:
CSort(int n) {
len = n;
arr = new int[len];
srand(time(NULL)); // 生成随机种子
for (int i = 0; i < len; i++) {
arr[i] = rand() % 100; // 生成随机数
}
}
~CSort() {
delete[] arr;
}
void bubbleSort() {
clock_t start, end;
start = clock();
for (int i = 0; i < len - 1; i++) {
for (int j = 0; j < len - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr[j], arr[j + 1]);
}
}
}
end = clock();
cout << "冒泡排序时间为:" << (double)(end - start) / CLOCKS_PER_SEC << "秒" << endl;
}
void selectionSort() {
clock_t start, end;
start = clock();
for (int i = 0; i < len - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < len; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
swap(arr[i], arr[minIndex]);
}
end = clock();
cout << "选择排序时间为:" << (double)(end - start) / CLOCKS_PER_SEC << "秒" << endl;
}
void insertionSort() {
clock_t start, end;
start = clock();
for (int i = 1; i < len; i++) {
int temp = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > temp) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = temp;
}
end = clock();
cout << "插入排序时间为:" << (double)(end - start) / CLOCKS_PER_SEC << "秒" << endl;
}
void print() {
for (int i = 0; i < len; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
};
int main() {
int n;
cout << "请输入待排序序列的长度:";
cin >> n;
CSort s(n);
cout << "待排序序列为:";
s.print();
s.bubbleSort();
s.print();
s.selectionSort();
s.print();
s.insertionSort();
s.print();
return 0;
}
阅读全文