引用 皆我百晓生 小程序回复内容作答:
下面是用迭代算法和递归算法分别实现整数的冒泡排序的示例代码:
- 迭代算法实现冒泡排序:
#include <iostream>
#include <ctime>
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
// Swap arr[j] and arr[j+1]
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
int main() {
int arr[1000]; // or int arr[10000];
// Initialize array with random or reverse sorted elements
// ...
clock_t start = clock();
bubbleSort(arr, 1000); // or bubbleSort(arr, 10000);
clock_t end = clock();
double time = double(end - start) / CLOCKS_PER_SEC;
std::cout << "Time taken: " << time << " seconds" << std::endl;
return 0;
}
- 递归算法实现冒泡排序:
#include <iostream>
#include <ctime>
void bubbleSortRecursive(int arr[], int n) {
if (n == 1) {
return;
}
for (int i = 0; i < n-1; i++) {
if (arr[i] > arr[i+1]) {
// Swap arr[i] and arr[i+1]
int temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
}
}
bubbleSortRecursive(arr, n-1);
}
int main() {
int arr[1000]; // or int arr[10000];
// Initialize array with random or reverse sorted elements
// ...
clock_t start = clock();
bubbleSortRecursive(arr, 1000); // or bubbleSortRecursive(arr, 10000);
clock_t end = clock();
double time = double(end - start) / CLOCKS_PER_SEC;
std::cout << "Time taken: " << time << " seconds" << std::endl;
return 0;
}
需要注意的是,在示例代码中需要根据要排序的整数个数自行初始化数组。另外,如果要比较不同数据元素分布情况下不同长度整数元素排序的运算时间,可以在相应位置进行修改。