-1

コードの何が問題になっているのかわかりませんが、再帰が開始される30行目でプログラムが中断し、ソートされていない配列のみが出力され、quickSortアルゴリズムが終了しません。このプログラムが正しく機能しない理由について誰かが何か手がかりを持っているなら、私に知らせてください。前もって感謝します。

#include <iostream>
#include <time.h>
using namespace std;

void quickSort(int qarray[], int l, int r){

    int i = l, j = r;
    int temp;
    int pivot = qarray[(l+r)]/2;

    //partitioning
    while(i<=j){
        while(qarray[i]< pivot)
            i++;
        while(qarray[j] > pivot)
            j--;
        if(i<=j){

            temp = qarray[i];
            qarray[i] = qarray[j];
            qarray[j] = temp;
            i++;
            j--;

        }
      }
    //Recursion of the quicksort algorithm
    if(l < j){

        quickSort(qarray,l,j);

    }
    if(i < r){

        quickSort(qarray,i,r);

    }

}

int main(){

    clock_t tStart = clock();

    int myArray[26] ={4,2,5,6,1,3,17,14,67,45,32,66,88,
                   78,69,92,93,21,25,23,71,61,59,60,30,79}; 

    for(int i=0;i < 26;i++){

        cout << "Unsorted: " << myArray[i] << endl;
    }


    quickSort(myArray,0,25);

    for(int i=0;i < 26;i++){

        cout << "Sorted: " << myArray[i] << endl;
    }


    double seconds = clock() / double(CLK_TCK);
    cout << "This program has been running for " << seconds << " seconds." << endl;

    system("pause");
    return 0;
}
4

1 に答える 1

4

この行のエラー(少なくとも):int pivot = qarray[(l+r)]/2;

でなければなりませんint pivot = qarray[(l + r) / 2];

配列の要素を2で割る意味はありません。ピボットは、インデックスがである範囲の中央の要素です(l + r) / 2

于 2012-09-04T16:56:35.373 に答える