【问题标题】:Sort Stack Overflow and Number of Compares and Swaps Negative排序堆栈溢出和比较次数和交换负数
【发布时间】:2011-09-15 15:08:52
【问题描述】:

我写了这个冒泡排序并在一个测试程序中使用它,该程序根据用户输入的数量在列表中给出随机数。然后给它一个包含 10,000 个随机整数的列表,并在第 55 行“if (swaps != 0){sort();}”返回堆栈溢出,这是为什么。有时它也有效,但返回的 myCompares 和 mySwaps 值为负。你能帮忙吗?

public class Bubbly {

    private int[] sortedList;
    private static long myTime = 0;
    private static int myCompares = 0;
    private static int mySwaps = 0;

    public Bubbly(int[] list) {
        sortedList = list;
        StopWatch stop = new StopWatch();
        stop.start();
        sort();
        stop.stop();
        myTime = stop.getElapsedTime();
    }

    public int[] getList(){
        return sortedList;
    }
    public long getTime(){
        return myTime;
    }

    public int getCompares(){
        return myCompares;
    }

    public int getSwaps(){
        return mySwaps;
    }

    public void sort(){
        int length = sortedList.length, i = 0, num, swaps = 0;

        while (i < length - 1){
            if (sortedList[i] > sortedList[i + 1]) {
                myCompares++;

                num = sortedList[i];
                sortedList[i] = sortedList[i+1];
                sortedList[i+1] = num;
                swaps++;
                mySwaps++;
            }
            myCompares++;
            i++;
        }

        if (swaps != 0){
            sort();
        }

    }
}

【问题讨论】:

    标签: c++ sorting int stack-overflow bubble-sort


    【解决方案1】:

    你的程序是递归的,可能是我见过的第一个递归冒泡排序 :-)

    递归意味着函数在工作完成之前不会返回,而是每次调用 sort() 时都会将额外的调用压入堆栈。在多次递归调用之后,堆栈已满并溢出。

    所以,去掉递归,这里没用,用循环就好了。

    关于获得负值的变量,首先要去掉 mySwaps、myTime 和 myCompare 上的 static 修饰符,因为它会阻止它们在每次测试运行时正确初始化。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-09
      • 2018-05-16
      • 1970-01-01
      • 1970-01-01
      • 2013-03-10
      • 2010-10-30
      • 2021-01-19
      • 2018-05-10
      相关资源
      最近更新 更多