我实现Quicksort方法时堆栈溢出

时间:2015-11-19 02:38:05

标签: java algorithm recursion stack-overflow quicksort

您好我正在尝试在Java中实现Quicksort方法,但出于某种原因,当我只做5个元素时,我收到了堆栈溢出错误!什么想法可能是错的? 我的代码的一部分:

class QuickSort implements AbstractSort {
    public int partition(int[] numbers, int start, int end)
    {
        int pivot = numbers[end];
        int theIndex = start;
        int temp;
        for(int i = start; i <= end - 1; i++)
        {
            if(numbers[i] <= pivot)
            {
                temp = numbers[theIndex];
                numbers[theIndex] = numbers[i];
                numbers[i] = temp;
                theIndex++;
            }
        }
        temp = numbers[theIndex];
        numbers[theIndex] = pivot;
        numbers[end] = temp;
        return theIndex;
    }

    public void mySort(int[] numbers, int start, int end)
    {
        if(start < end)
        {
            int myIndex = partition(numbers, start, end);

            mySort(numbers, 0, myIndex-1);
            mySort(numbers, myIndex + 1, numbers.length - 1);
        }
        else
        {
            return;
        }
    }
    public void sort(int[] numbers) 
    {
        mySort(numbers, 0, numbers.length - 1);
    }
}

1 个答案:

答案 0 :(得分:1)

问题出在mySort(numbers, 0, myIndex-1);我应该将start设置为0而不是0,所以正确的代码看起来像这样mySort(numbers, start, myIndex-1);

相关问题