You are viewing a single comment's thread. Return to all comments →
#include <bits/stdc++.h> using namespace std; long long insertionSortShifts(vector<int> arr) { long long shifts = 0; int n = arr.size(); for (int i = 1; i < n; i++) { int value = arr[i]; int j = i - 1; while (j >= 0 && arr[j] > value) { arr[j + 1] = arr[j]; shifts++; j--; } arr[j + 1] = value; } return shifts; } int partition(vector<int> &arr, int l, int h, long long &swaps) { int pivot = arr[h]; int i = l; for (int j = l; j < h; j++) { if (arr[j] <= pivot) { swap(arr[i], arr[j]); swaps++; i++; } } swap(arr[i], arr[h]); swaps++; return i; } void quickSort(vector<int> &arr, int l, int h, long long &swaps) { if (l < h) { int p = partition(arr, l, h, swaps); quickSort(arr, l, p - 1, swaps); quickSort(arr, p + 1, h, swaps); } } int main() { int n; cin >> n; vector<int> arr(n), arrCopy(n); for (int i = 0; i < n; i++) { cin >> arr[i]; arrCopy[i] = arr[i]; } long long shifts = insertionSortShifts(arrCopy); long long swaps = 0; quickSort(arr, 0, n - 1, swaps); cout << (shifts - swaps) << "\n"; return 0; }
Seems like cookies are disabled on this browser, please enable them to open this website
Running Time of Quicksort
You are viewing a single comment's thread. Return to all comments →