C++选择排序和冒泡排序加入统计比较次数和交换次数的代码
时间: 2024-09-20 14:07:22 浏览: 42
bubble sorting冒泡算法,c++
C++ 中的选择排序和冒泡排序算法都会涉及到比较元素和可能的交换操作。下面是两个简单版本的代码,分别记录了比较次数和交换次数:
### 选择排序(Selection Sort)
```cpp
#include <iostream>
void selectionSort(int arr[], int n, int& comparisons, int& swaps) {
for (int i = 0; i < n - 1; ++i) {
int min_idx = i;
for (int j = i + 1; j < n; ++j) {
comparisons++; // 比较次数加一
if (arr[j] < arr[min_idx])
min_idx = j;
}
if (min_idx != i)
swaps++; // 如果有交换,交换次数加一
std::swap(arr[i], arr[min_idx]);
}
}
// 示例用法
int main() {
int arr[] = {5, 2, 8, 3, 9};
int n = sizeof(arr) / sizeof(arr[0]);
int comparisons = 0, swaps = 0;
selectionSort(arr, n, comparisons, swaps);
std::cout << "Sorted array: ";
for (int i : arr)
std::cout << i << " ";
std::cout << "\nComparisons: " << comparisons << ", Swaps: " << swaps << std::endl;
return 0;
}
```
### 冒泡排序(Bubble Sort)
```cpp
#include <iostream>
void bubbleSort(int arr[], int n, int& comparisons, int& swaps) {
for (int i = 0; i < n - 1; ++i) {
for (int j = 0; j < n - 1 - i; ++j) {
comparisons++; // 比较次数加一
if (arr[j] > arr[j + 1]) {
swaps++; // 如果有交换,交换次数加一
std::swap(arr[j], arr[j + 1]);
}
}
}
}
// 示例用法
int main() {
int arr[] = {5, 2, 8, 3, 9};
int n = sizeof(arr) / sizeof(arr[0]);
int comparisons = 0, swaps = 0;
bubbleSort(arr, n, comparisons, swaps);
std::cout << "Sorted array: ";
for (int i : arr)
std::cout << i << " ";
std::cout << "\nComparisons: " << comparisons << ", Swaps: " << swaps << std::endl;
return 0;
}
```
这两个函数会在排序过程中递增`comparisons`和`swaps`变量,并在主函数中输出结果。
阅读全文