C++ 利用随机数生成函数,产生待排序序列,序列长度可任意指定 设计CSort类 ,完成冒泡排序、选择排序和插入排序三种排序方法设计 调用系统函数,实现算法运行时间统计
时间: 2024-05-20 19:16:53 浏览: 15
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
class CSort {
public:
// 冒泡排序
void bubbleSort(int arr[], int len) {
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]);
}
}
}
}
// 选择排序
void selectionSort(int arr[], int len) {
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;
}
}
if (minIndex != i) {
swap(arr[i], arr[minIndex]);
}
}
}
// 插入排序
void insertionSort(int arr[], int len) {
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;
}
}
// 生成随机数序列
void generateRandomArray(int arr[], int len) {
srand(time(NULL));
for (int i = 0; i < len; i++) {
arr[i] = rand() % 100; // 生成 0-99 的随机数
}
}
};
int main() {
CSort sort;
int len = 10; // 序列长度
int arr[len];
sort.generateRandomArray(arr, len);
cout << "随机数序列为: ";
for (int i = 0; i < len; i++) {
cout << arr[i] << " ";
}
cout << endl;
// 冒泡排序
clock_t start = clock();
sort.bubbleSort(arr, len);
clock_t end = clock();
double time = (double) (end - start) / CLOCKS_PER_SEC;
cout << "冒泡排序结果为: ";
for (int i = 0; i < len; i++) {
cout << arr[i] << " ";
}
cout << endl;
cout << "冒泡排序运行时间为: " << time << "s" << endl;
// 选择排序
sort.generateRandomArray(arr, len);
start = clock();
sort.selectionSort(arr, len);
end = clock();
time = (double) (end - start) / CLOCKS_PER_SEC;
cout << "选择排序结果为: ";
for (int i = 0; i < len; i++) {
cout << arr[i] << " ";
}
cout << endl;
cout << "选择排序运行时间为: " << time << "s" << endl;
// 插入排序
sort.generateRandomArray(arr, len);
start = clock();
sort.insertionSort(arr, len);
end = clock();
time = (double) (end - start) / CLOCKS_PER_SEC;
cout << "插入排序结果为: ";
for (int i = 0; i < len; i++) {
cout << arr[i] << " ";
}
cout << endl;
cout << "插入排序运行时间为: " << time << "s" << endl;
return 0;
}