Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cstring>
- #include <cassert>
- #include <algorithm>
- int partition(int arr[], int l, int r, long long x) {
- int i;
- for (i = l; i <= r - 1; ++i) {
- if (x == arr[i]) {
- break;
- }
- }
- std::swap(arr[r], arr[i]);
- i = l;
- for (int j = l; j <= r - 1; ++j) {
- if (x <= arr[j]) {
- continue;
- } else {
- std::swap(arr[j], arr[i]);
- ++i;
- }
- }
- std::swap(arr[r], arr[i]);
- return i;
- }
- int findMedian(int arr[], int n) {
- std::sort(arr, arr+n);
- return arr[n/2];
- }
- int QuickSelect(int arr[], int left, int right) {
- int size = right - left + 1;
- int i;
- int median[(size + 4) / 5];
- for (i = 0; i < size / 5; i++) {
- median[i] = findMedian(arr + left + i * 5, 5);
- }
- // if there is sub_array in the end with len less that 5
- if (i * 5 < size) {
- median[i] = findMedian(arr + left + i * 5, size % 5);
- ++i;
- }
- int mediansOfMedians;
- if (i == 1) {
- mediansOfMedians = median[0];
- } else {
- mediansOfMedians = QuickSelect(median, 0, i - 1);
- }
- return mediansOfMedians;
- }
- void QuickSort(int arr[], int left, int right) {
- if (left >= right) return;
- if (left < right) {
- int pivot = QuickSelect(arr, left, right);
- int ind = partition(arr, left, right, pivot);
- QuickSort(arr, left, ind - 1);
- QuickSort(arr, ind + 1, right);
- //return ind;
- }
- }
- int main() {
- std::ios_base::sync_with_stdio(false);
- std::cin.tie(nullptr);
- std::cout.tie(nullptr);
- int n;
- std::cin >> n;
- int* array = new int[n];
- for (int i = 0; i < n; ++i) {
- std::cin >> array[i];
- }
- //std::cout << QuickSelect(array, 0, n - 1) << "\n";
- QuickSort(array, 0, n - 1);
- for (int i = 0; i < n; ++i) {
- std::cout << array[i] << " ";
- }
- delete[] array;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement