-2

このプログラムはコンパイル時にエラーを表示しています。何が問題なのか教えていただけますか?

メインクラス:

import java.util.Scanner;
public class Sortingpro {
    public static void main(String[] args) {
        Scanner input=new Scanner(System.in);
        System.out.println("Enter the number of elements");
        int a=input.nextInt();
        int A[]=new int[a];
        System.out.println("Enter the elements");
        for(int i=0;i<a;i++){
            A[i]=input.nextInt();
        }
        sort quick=new sort(A,a);
        quick.display(A,a);
    }
}

ソートクラス:

public class sort {
    int A[],size;
    sort(int a[],int s){
        this.A=a;
        this.size=s;
        quickSort(a,1,s);
    }
    void quickSort(int a[],int p,int r){
        while(p<r){
            int q;
            q=Partition(A,p,r);
            quickSort(A,p,q-1);
            quickSort(A,q+1,r);
        }
    }

    int Partition(int a[],int p,int r)
    {
        int x=a[r];
        int i=p-1;
        for(int j=p;j<r;j++){
            if(a[j]<=x){
                i+=1;
                int temp=a[i];
                a[i]=a[j];
                a[j]=temp;
            }
        }
        int temp=a[i+1];
        a[i+1]=a[r];
        a[r]=temp;
        return i=1;
    };
    void display(int A[],int size){
        this.A=A;
        this.size=size;
        for(int i=0;i<size;i++){
            System.out.println(A);
        }
    }

}

例外。

*****The sorting algorithm used is from CLRS.
      I am getting the following errors through Netbeans:
      Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
      at sortingpro.sort.Partition(sort.java:31)
      at sortingpro.sort.quickSort(sort.java:23)
      at sortingpro.sort.<init>(sort.java:17)
      at sortingpro.Sortingpro.main(Sortingpro.java:26)

      Can you please elaborate on these errors and the remedial methods to be undertaken to solve                    the problem? Also any better methods to implement this program,coding wise?

アルゴリズムに関する提案も歓迎しますが、プログラムの本質を維持することを好みます。


4

1 に答える 1

2

それがスタックトレースです:

10個の要素を入力した場合のように、最大​​サイズでクイックソートを呼び出し、10でsを呼び出しました

quickSort(a,1,s);

これは順番に呼び出します

q=Partition(A,p,r);

r が 10 の場合、array[r] を使用します。

配列はインデックス 0 から始まり、あなたのケースでは r-1 まで続くため、ArrayIndexOutOfBound 例外が発生します。したがって、最後のパラメーターとして s-1 を指定し、開始インデックスとして 0 を指定してクイックソート メソッドを呼び出します。

quickSort(a,0,s-1);

また、再帰的なソリューションでは、if である必要がある while ループを使用しています。したがって、クイックソートは次のようになります。

void quickSort(int a[],int p,int r){
    if(p<r){
        int q;
        q=Partition(A,p,r);
        quickSort(A,p,q-1);
        quickSort(A,q+1,r);
    }
}
于 2014-11-16T08:00:12.997 に答える