#include #include

using namespace std;

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

int comparisons = 0;
int swapCount = 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++;
        swapCount++; // 在交换时递增交换次数
    }
}

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

comparisons += quickSortComparisons(arr, start, j - 1);
comparisons += quickSortComparisons(arr, j + 1, end);

return comparisons + swapCount; // 将交换次数加入总计数中

}

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;

}

// 输入 // 5 // 2 5 4 3 1

// 输出 // 7

C++ 快速排序比较次数计算:优化代码和注释

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

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