首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >quickSort - StackOverflowException

quickSort - StackOverflowException
EN

Stack Overflow用户
提问于 2013-02-16 05:34:53
回答 1查看 189关注 0票数 1

我正在试着写一个快速排序算法。请看下面的代码:

代码语言:javascript
复制
public static void quickSort(int[] tab, int lowIndex, int highIndex) {
    if (tab.length == 0 || tab == null) {
        return;
    }

    int i = lowIndex;
    int j = highIndex;

    int pivot = tab[tab.length / 2];

    while (i <= j) {
        while (tab[i] < pivot) {
            i++;
        }
        while (tab[j] > pivot) {
            j--;
        }

        if (i <= j) {
            int c = tab[i];
            tab[i] = tab[j];
            tab[j] = c;
            i++;
            j--;
        }

        if (lowIndex < j) {
            quickSort(tab, lowIndex, j); // error !!!
        }
        if (i < highIndex) {
            quickSort(tab, i, highIndex);
        }
    }

}

问题是线程"main“java.lang.StackOverflowError中的异常。出什么问题了?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-02-16 05:41:42

这是错误的:

代码语言:javascript
复制
int pivot = tab[tab.length / 2];

您必须在提供的切片中查找轴心,而不是在tab中全局查找。

代码语言:javascript
复制
int pivot = tab[lowIndex + (highIndex - lowIndex)/ 2];

此外,您终止递归的条件也是错误的。表的长度不变。您必须检查lowIndex >= highIndex是否

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14903687

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档