#include #include

using namespace std;

int quickSortComparisons(vector& arr, int start, int end) { if (start >= end) { return 0; }

int comparisons = 0;
int swaps = 0;
int pivot = arr[start];
int i = start + 1;
int j = end;

while (i <= j) {
    if (arr[i] <= pivot) {
        i++;
        comparisons++;
    } else if (arr[j] > pivot) {
        j--;
        comparisons++;
    } else {
        swap(arr[i], arr[j]);
        i++;
        j--;
        comparisons++;
        swaps++;
    }
}

swap(arr[start], arr[j]);

comparisons += quickSortComparisons(arr, start, j - 1);
comparisons += quickSortComparisons(arr, j + 1, end);
swaps += j - start - 1; // 加入递归过程中的交换次数

return comparisons + swaps;

}

int main() { int n; cin >> n;

vector<int> arr(n);
for (int i = 0; i < n; i++) {
    cin >> arr[i];
}

int comparisons = quickSortComparisons(arr, 0, n - 1);
cout << comparisons << endl;

return 0;

}

该代码实现了一个快速排序算法,并计算了排序过程中元素比较的次数。

问题:

最初的代码在计算交换次数时只考虑了交换操作本身,而没有考虑递归过程中的交换次数。这会导致交换次数的统计不准确。

解决方案:

为了解决这个问题,需要将递归过程中的交换次数也加入到总计数中。修改后的代码在 quickSortComparisons 函数中,在递归调用后增加了 swaps += j - start - 1; 这行代码,用来统计每次递归过程中的交换次数。

示例:

输入:

5
2 5 4 3 1

输出:

7

优化后的代码能够准确地统计快速排序算法中的交换次数。

C++ 快速排序算法:比较次数计算优化

原文地址: https://www.cveoy.top/t/topic/omqD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录