C ++递归Quicksort无限循环

基兰丹9

因此,我一直在使用c ++程序对整数数组进行快速排序的问题。当我的数组中有六个以上元素时,由于某种原因,排序将无限循环。我认为我已经将问题与mm关键值的选择隔离开了,但是我无法终生弄清楚为什么它会导致折断。

#include<iostream>
using namespace std;

int getPivot(int begin,int end){//Takes length of array as input and returns the position of the pivot
    int len = end-begin;
    if(len < 3){
        return end;
    }else{
        return 2;
    }
};

void quickSort(int begin, int end, int arr[]){
    int pivot = arr[getPivot(begin,end)];//get Pivotal value - If I replace this with just 0 then there are no problems...
    int tempLeft = begin, tempRight = end;
    int temp;
    while(tempLeft <= tempRight){
        while(arr[tempLeft] < pivot){//Find a point where there are 2 elements that need to be swapped
            tempLeft++;
        }
        while(arr[tempRight] > pivot){
            tempRight--;
        }
        if(tempLeft <= tempRight){
            temp = arr[tempLeft];//Swap the elements
            arr[tempLeft] = arr[tempRight];
            arr[tempRight] = temp;
            tempLeft++;//Skip these swapped elements in the sort
            tempRight--;
        }
    }
    if (begin < tempRight){//Only recurse lower if the new sub array has a length greater than 1
        quickSort(begin, tempRight, arr);
    }
    if (tempLeft < end){
        quickSort(tempLeft, end, arr);
    }
}

main() {
    int array[] = {0,1,2,3,4,5,6};
    int length = 7;
    quickSort(0,length-1,array);
}

您可能会问,为什么我有这样一种奇怪的方式来选择我的枢轴值,但只能说,在这种情况下,枢轴值必须是每个子列表中的第三个元素,或者如果子列表小于3,则它是最后一个子列表中的项目。

我认为该问题与关键值相关联的原因是,当我仅使用子列表中的第一个元素替换我选择关键点的方法时,我没有任何问题。

如果运行,就像现在的程序一样,将在无限循环后发生段错误,但是如果要排序的数组短一个元素,它将正常工作。那已经让我困惑了几个小时,而我无法弄清问题出在哪里。如果有人有任何提示或建议,将不胜感激。

洛伦佐·贝利(Lorenzo Belli)

quickSort(3,6,arr)会一直打电话quickSort(3,6,arr)

我想你想念

int getPivot(int begin,int end)
{
    //Takes length of array as input and returns the position of the pivot
    int len = end-begin;
    if(len < 3){
        return end;
    }else{
        return 2+begin; // Here
    }
};

编辑:澄清

GetPivot(3,6) 将返回2,而应返回3到6之间的索引。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章