私のクイックソートの実装を使用して誕生日のベクトルをソートしようとしています。また、変更方法に基づいて名前と誕生日を含む2つのベクトルの順序を変更します。私はクイックソートを実装する方法についてのオンラインソースをたどってきましたが、なぜそれがうまくいかないのか正確にはわかりません。ここに私のコードです:クイックソートテンプレートが機能せず、プログラムが応答しなくなる
template <class T>
void sortBDay(vector<T> &birthday, vector<string> &name, vector<T> &birthdate, int startPos, int size) { // This template sorts all data by their birthday
if (startPos < size - 1) { // if the first value is less than the last value
T pivotVal = birthday[startPos]; // the pivot value is the vector's first value
int pivotPos = startPos; // the pivot position is the vector's starting position
for (int pos = startPos + 1; pos <= size; pos++) { // repeat for all values of vector
if (birthday[pos] < pivotVal) { // if the current position is less than the starting position
swap(birthday[pivotPos + 1], birthday[pos]);
swap(birthday[pivotPos], birthday[pivotPos + 1]); // switch the positions
swap(name[pivotPos + 1], name[pos]); // and their names
swap(name[pivotPos], name[pivotPos + 1]);
swap(birthdate[pivotPos + 1], birthdate[pos]); // and their birthdates
swap(birthdate[pivotPos], birthdate[pivotPos + 1]);
pivotPos++; // then go onto the next one
}
sortBDay(birthday, name, birthdate, startPos, size - 1); // do the same for upper and lower pivots
sortBDay(birthday, name, birthdate, startPos, size + 1); // recursion
}
}
}
私はこの実装に何が問題なのか分かりません。どんな助けもありがとう!前もって感謝します。
'pos <= size' - それはまったくよく見えません。このデータがすべて3つの異なるベクトルではなく、オブジェクトの単一のベクトルに含まれていれば、これはかなりきれいになります。そしてfwiw、['std :: partition'](http://en.cppreference.com/w/cpp/algorithm/partition)はクイックソートアルゴリズムの短期間の作業を行い、ここでの間違いを取り除いています。リンクされたドキュメントには、それだけでも使用例があります。 quicksortを実装します。 – WhozCraig
別々のパーティション機能を追加する必要がありますか、それともすべて一緒に保つことはできますか? – Cool
独自のパーティションアルゴリズムを使用したい場合は、すべて一緒に保つことができます。 – WhozCraig