c++代码实树形选择排序中比较次数和移动次数的计算
以下是C++代码实现树形选择排序,并计算比较次数和移动次数的示例:
#include <iostream>
using namespace std;
int comparisonCount = 0; // 比较次数计数器
int moveCount = 0; // 移动次数计数器
void treeSelectionSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
int minIndex = i; // 最小值的下标
for (int j = i + 1; j < n; j++) {
comparisonCount++; // 每次比较都增加计数器
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
if (minIndex != i) {
swap(arr[minIndex], arr[i]); // 交换元素
moveCount += 3; // 每次交换都增加计数器
}
}
}
int main() {
int arr[] = { 5, 2, 8, 3, 9, 1, 6, 0, 7, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
treeSelectionSort(arr, n);
cout << "Sorted array: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
cout << "Comparison count: " << comparisonCount << endl;
cout << "Move count: " << moveCount << endl;
return 0;
}
在上述代码中,我们使用两个计数器变量 comparisonCount 和 moveCount 分别记录比较次数和移动次数。在每次比较和移动操作中,我们都更新这两个计数器的值。最后在程序末尾输出这两个计数器的值即可
原文地址: https://www.cveoy.top/t/topic/cYST 著作权归作者所有。请勿转载和采集!