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

标签 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 ");
}

}

最佳答案

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

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

关于java - 为什么会出现堆栈溢出错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21221105/

相关文章:

java - ImageView onTouchListener : cant touch the imageview behind

java - Xpath:选择所有元素类型?

java - 按钮未出现在 JFrame 中

java.lang.StackOverflowError 在 Weblogic 12c 上运行 JSF 2 示例

c - 如何调试目标上的 stackoverflow 问题

c - C中链表的快速排序

java - Log4j 日志在错误的文件中滚动(在当天之前,跳过周末)

JavaFX 鼠标位置

android - 在 Activity 堆叠之前终止 Activity,因此召回 Activity 不会导致溢出

c# - 为什么将 DoEvents 放入循环中会导致 StackOverflow 异常?