C++ 随机快速排序段错误

标签 c++ sorting random quicksort

我正在使用 C++ 编写一个随机快速排序程序,但由于某种原因,程序会出现段错误,我不太明白为什么。

我很确定它与我的 hoarePartition 函数有关,陷入了 while 循环,但我不确定问题出在哪里。

解决这个问题的任何帮助都会非常有帮助!

#import <iostream>
#import <cstdlib>
#import <random>
#import <time.h>
#include <ctime>
#include <boost/timer.hpp>

void swap(int& first, int& second)
{
    int temp = first; 
    first = second; 
    second = temp;
}

int hoarePartition(int* array, int leftIndex, int rightIndex)
{
    int partition = array[leftIndex];
    int i = leftIndex;
    int j = rightIndex + 1;

    while (i < j)
    {
        while (array[i] < partition && i <= j)
        {
            i = i + 1;
        }
        while (array[j] > partition && j > i)
        {
            j = j - 1;
            cout << j << endl;
        }
        swap(array[i], array[j]);
    }

    swap(array[i], array[j]);
    swap(array[leftIndex], array[j]);

    return j;
}

void randomQuickSort(int* array, int leftIndex, int rightIndex)
{
    if (leftIndex < rightIndex)
    {
        int q = rand() % (rightIndex - leftIndex) + leftIndex;
        swap(array[leftIndex], array[q]);
        int s = hoarePartition(array, leftIndex, rightIndex);
        randomQuickSort(array, leftIndex, s-1);
        randomQuickSort(array, s+1, rightIndex);
    }
}

int main(int argc, char** argv)
{
    srand(time(NULL));
    int size = atoi(argv[1]);
    int* array = new int[size];

    for (int i = 0; i < size; ++i) 
    {
        array[i] = (100.0 * rand()) / RAND_MAX;
    }

    boost::timer t;
    randomQuickSort(array, 0, size);
    std::cout << t.elapsed() << endl;

    delete[] array;

    return 0;
}

最佳答案

您使用 rightIndex=size 调用 randomQuickSort,它比数组中最后一个元素的索引大一个。然后,将其传递给 hoarePartition,将 j 初始化为 rightIndex+1,然后(在第二个内部 while 循环)访问 array[j]

关于C++ 随机快速排序段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28612871/

相关文章:

c++ - std::getline 和 std::vector<std::string> 的奇怪行为

javascript - AHK GUI DateTime 默认设置

mongodb - Mongo分页

python-3.x - os.urandom 使用 Python 的 random 模块是否有可预测的替代品?

c++ - static_assert 有什么作用,你会用它做什么?

单击按钮时出现 java.lang.NumberFormatException

algorithm - 有效分配项目和满足最小值的已知算法?

XPATH 选择随机数量的节点并且有多个条件

java - Java Random 和 Kotlin Random 的区别

c++ - 重新 -'new' TCHAR* 数组