-1

クイックソートを実装する C++ コードを書きました。コンパイルはできますが、実行時にクラッシュします。コードブロックを使用しました。デバッガーを使用すると、次のように表示されます。

行 (45) の「セグメンテーション違反」"q=Partition(r,n);" パーティション関数の定義で。

私はそれを検索し、いくつかの答えを見つけましたが、ここで私の問題を解決したものはありませんでした. このプログラムが実行されない理由を教えてください。

//Program for Quicksort

#include <iostream>

using namespace std;

int Partition(int* p,int n);
void Qsort(int* p,int n);
void Swap(int* a,int* b);

int main()
{
    int n=0;                                              //array size
    cout<<"Enter array size\n";
    cin>>n;
    int a[n];
    cout<<"Now enter the array elements\n";
    for(int i=0;i<n;i++)                                
        cin>>a[i];                                        //read array
    int *p;
    p=a;
    Qsort(p,n);                                           //call Qsort, args:pointer to 
    cout<<"This is the sorted array:\n";                  //array, array size
    for(int i=0;i<n;i++)
        cout<<a[i]<<" "<<endl;                            //print sorted array
    return 0;
}
int Partition(int* p,int n)                               //the partition function
{
    int key=*(p+n-1);
    int i=-1,j=0;
    for(j=0;j<n-1;j++)
    {
        if(*(p+j)<=key)
            {
                i++;
                Swap(p+i,p+j);
            }
    }

    *(p+i+1)=key;
    return i+1;
}
void Qsort(int* r,int n)
{
    int q=0;
    q=Partition(r,n);                          //The debugger points here and says 
    Qsort(r,q);                                //there is a segmentation fault
    Qsort(r+q+1,n-q-1);
}

void Swap(int* a,int* b)                       //To exchange two integer variables
{
    int t=0;
    t=*a;
    *a=*b;
    *b=t;
}
4

1 に答える 1