为什么会出现堆栈溢出错误?

时间:2014-01-19 18:52:42

标签: java stack-overflow

这是代码..我必须对已经排序的数组进行排序并计算它的执行时间...对于快速排序它是n ^ 2,因为它是最坏的情况。但对于大输入数据,让我们说7500它给我一个溢出错误:S我能做些什么来计算运行时间?

public class Provo {

    public static void swap(int[] a, int i, int j) {
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }

    public static int HoarePartition(int m, int d, int[] a) {
        int pivot = a[m];
        int i = m + 1;
        int j = d;

        while (i < j) {
            while (a[i] < pivot) {
                i = i + 1;
            }

            while (a[j] > pivot) {
                j = j - 1;
            }

            if (i < j)
                swap(a, i, j);
        }
        swap(a, m, j);

        return j;
    }

    public static void quicksort(int m, int d, int[] a) {
        if (m < d) {
            int s = HoarePartition(m, d, a);
            quicksort(m, s - 1, a);
            quicksort(s + 1, d, a);
        }
    }
}

这是主要的课程

import javax.swing.*;

public class ascending {


public static void main(String[] args){
    String input=JOptionPane.showInputDialog("Shkruani nr e te dhenave");
    int size=new Integer(input).intValue();

    int[] r= new int[size];
    int[] p = new int[size];
    int majtas=0;
    int djathtas=size;

    for(int i=majtas;i<djathtas;i++)
    {r[i]=i;}
    for(int i=majtas;i<djathtas;i++)
    {p[i]=r[i];}

    long average;
    int n=100;
    long result=0;
    for(int j=1;j<=n;j++) 
    {
        long startTime = System.nanoTime();
        Provo.quicksort(majtas,djathtas-1,p);
     long endTime = System.nanoTime();
     result = result+(endTime-startTime);
   long a = endTime-startTime;
        System.out.println(j+": " +a);
        for(int i=majtas;i<djathtas;i++)
        {p[i]=r[i];}
    }
    average=result/n;
    System.out.println("Koha e ekzekutimit te insertion sort eshte " + average + " nanosekonda ");
}

}

2 个答案:

答案 0 :(得分:1)

如果您遇到困难,您可以在网上寻找 迭代快速排序 以获得一些帮助。

我找到了article。它专门用于C#,但将其转换为Java应该不是一个大问题。

答案 1 :(得分:0)

int djathtas = size - 1;更改为int djathtas = size;,将change quicksort(majtas, djathtas, p);更改为quicksort(majtas, djathtas - 1, p);

否则它不会分配10位数,只有9位。

看起来你只是使用了太多的数字。您的程序可以正常运行并生成堆栈溢出错误。您可以尝试实现不依赖于堆栈的其他版本的快速排序。

除此之外,我不知道为什么你还需要这么大的输入。

相关问题