Ich versuche, einen Vektor von Geburtstagen (mit meiner Implementierung von Quicksort) zu sortieren, und ändern Sie auch die Reihenfolge der zwei Vektoren mit Namen und Geburtsdaten basierend darauf, wie sie sich ändern. Ich habe eine Online-Quelle über die Implementierung von Quicksort verfolgt, bin mir aber nicht ganz sicher, warum das nicht funktionieren wird. Hier ist mein Code:Quicksort-Vorlage funktioniert nicht, und mein Programm reagiert nicht
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
}
}
}
Ich weiß nicht, was ist falsch mit dieser Implementierung. Jede Hilfe wäre willkommen! Danke im Voraus.
'pos <= Größe' - das sieht gar nicht gut aus. Dies wäre wesentlich sauberer, wenn alle diese Daten in einem einzelnen Vektor von Objekten statt in drei verschiedenen Vektoren wären. Und fwiw, ['std :: partition'] (http://en.cppreference.com/w/cpp/algorithm/partition), macht den Quicksort-Algorithmus kurz und eliminiert die hier gemachten Fehler. Das verknüpfte Dokument hat sogar ein Verwendungsbeispiel, das genau das tut; implementiert Quicksort. – WhozCraig
Muss ich die separate Partitionsfunktion hinzufügen, oder kann ich alles zusammenhalten? – Cool
Sie können alles zusammenhalten, wenn Sie sicherlich Ihren eigenen Partitionsalgorithmus verwenden möchten. – WhozCraig