#include #include

using namespace std;

int quickSortSwaps(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]);

swaps += quickSortSwaps(arr, start, j - 1);
swaps += quickSortSwaps(arr, j + 1, end);

return swaps; // 返回交换次数

}

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

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

int swaps = quickSortSwaps(arr, 0, n - 1);
cout << swaps << endl;

return 0;

}

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

快速排序算法:交换次数统计

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

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