Сбой консоли Quicksort с отсортированным массивом - PullRequest
0 голосов
/ 13 июня 2019

Я пытаюсь составить график сложности времени, используя быструю сортировку до 50 000 номеров. Сортировка случайных чисел работает нормально. При сортировке массива already sorted по 4000 чисел я получаю Debug\QS.exe (process 2208) exited with code -1073741571.. Работает нормально с срединным разделителем. Проблема, вероятно, около Function uses '64000' bytes of stack: exceeds /analyze:stacksize '16000'. Consider moving some data to heap..

Мои знания низкие, поэтому я решил проблему с обычными массивами вместо usind std :: array или vector. Также для быстрой сортировки я использовал псевдокод, который мне дали. Как мне реализовать код для исправления «сбоя»?

РЕДАКТИРОВАТЬ: Для генерации массива в порядке возрастания я сначала сгенерировал случайный массив, а затем отсортировал его, что я считаю, есть лучшие подходы.

#include <iostream>
#include <string>
#include <random>
#include <algorithm>
#include <chrono>
#include <functional>

const int size = 50000;

std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> num(1, 1000000);

void swap(int* a, int* b) {
    int t = *a;
    *a = *b;
    *b = t;
}

void generateAscending(int* arr, int size) {
    for (int index = 0; index < size; index++) {
        arr[index] = num(gen);
    }
    std::sort(arr, arr + size);
}


bool check(int* arr, int low, int high) {
    for (int i = low; i < high - 1; i++) {
        if (arr[i + 1] < arr[i]) {
            return false;
        }
    }
    return true;
}


int partition(int* arr, int low, int high) {
    int pe = arr[low];
    int l = low;
    int d = high;
    while (l < d) {
        while (arr[l] <= pe && l < high) l++;
        while (arr[d] >= pe && d > low) d--;

        if (l < d) {
            swap(&arr[l], &arr[d]);
        }
    }
    swap(&arr[low], &arr[d]);
    return d;
}

int partition_median(int* arr, int low, int high) {
    int m = low + (high - low) / 2; // median pivot
    int pe = arr[m];
    int l = low;
    int d = high;
    swap(&arr[low], &arr[m]);
    while (l < d) {

        while (arr[l] <= pe && l < high) l++;
        while (arr[d] >= pe && d > low) d--;

        if (l < d) {
            swap(&arr[l], &arr[d]);
        }
    }
    swap(&arr[low], &arr[d]);
    return d;
}

void quickSort(int* arr, int low, int high) {
    if (low < high) {
        int j = partition(arr, low, high);
        quickSort(arr, low, j - 1);
        quickSort(arr, j + 1, high);
    }
}

void quickSort_median(int* arr, int low, int high) {
    if (low < high) {
        int j = partition_median(arr, low, high);
        quickSort_median(arr, low, j - 1);
        quickSort_median(arr, j + 1, high);
    }
}

int main(int argc, char* argv[]) {
    int arr[size];

    generateAscending(arr, size);

    // Check if in ascending order
    if (check(arr, 0, size - 1)) {
        std::cout << "Array is in ascending order." << '\n';
    }
    else {
        std::cout << "Array is not in ascending order." << '\n';
    }

    // Quick sort
    auto start = std::chrono::steady_clock::now();
    quickSort(arr, 0, size - 1);
    auto end = std::chrono::steady_clock::now();
    std::cout << "Time: " << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() << " microseconds." << '\n';

    /*
    // Quick sort median
    auto start = std::chrono::steady_clock::now();
    quickSort_median(arr, 0, size - 1);
    auto end = std::chrono::steady_clock::now();
    std::cout << "Time: " << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() << " microseconds." << '\n';            
    */

    if (check(arr, 0, size - 1)) {
        std::cout << "Array is in ascending order." << '\n';
    }
    else {
        std::cout << "Array is not in ascending order." << '\n';
    }

    return 0;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...