1

クイック選択のために次のコードを実行すると

#include <cstdlib>
#include <iostream>

using namespace std;
const int n = 15;
int b[100];
int btotal=0;
int c[100];
int ctotal=0;

void read(int a[],int size){
    for (int i=1; i<=15; i++) cin >> a[i];
}

int quickselect(int a[], int k)
{
    int r = 1 + rand()%(n-1);
    int pivot = a[r];
    for (int i=1; i<=n; i++) {
        if (a[i] < pivot) {
            b[i] = a[i];
            ++btotal;
        }

        if (a[i] > pivot) {
            c[i] = a[i];
            ++ctotal;
        }  
    }

    if (k <= btotal) quickselect(b,k);
    if (k > (n-ctotal)) return quickselect(c, k - (n-ctotal));        

    return pivot;          
}

int main(int argc, char *argv[])
{
    int a[n];
    cout <<" enter contents of array " << endl;
    read(a, n);
    quickselect(a, 6);
    //system("PAUSE");
    //return EXIT_SUCCESS;
    return 0;
}

1 4 2 3 5 7 6 9 8 10 13 12 11 15 14

実行時エラーが発生しました。インデックス作成に関連する問題だと思いますが、場所がわかりません。助けてください

4

1 に答える 1

2

array の範囲外に書き込んでいますa

int a[15]a[0]からまでの範囲のインデックスを使用して、15 個の整数用のスペースを割り当てますa[14][1]あなたは現在、オフセットへの(およびオフセットを含む)読み取り/書き込みを行っていますが、[15]これは間違っています。


最小限の変更が必要

void
read (int a[],int size)
{
  for (int i=0; i < 15; i++) // CHANGE TO
    ...
}

...

int
quickselect(int a[],int  k)
{
  ...

  for (int i=0; i < n; i++) { // CHANGE TO

  ...
}
于 2012-03-14T07:25:44.140 に答える