根据Cormen的Alghorithms简介,我正试图自己实施Quick Sort。 我有一个以下代码,但也有一个问题:
void quickSort(Node* left, Node* right) {
Node* start = left;
Node* cur = left->next;
if (left == right) return;
while (cur != right) {
if (start->data < cur->data) swap(start->data,cur->data);
cur = cur->next;
}
swap(left->data,cur->data);
Node* oldCur = cur;
cur = getPrevious(cur);
if (cur != nullptr && (getPrevious(left) != cur) && (cur->next != left)) quickSort(left,cur);
cur = oldCur->next;
if (cur != nullptr && (getPrevious(cur) != right) && (right->next != cur)) quickSort(cur, right);
}
对于均匀长度,它可以正常工作
7 6 5 8 4 3 2 1
1 2 3 4 5 6 7 8
但是对于奇数个输入数据,输出如下所示
7 6 5 8 4 2 1
1 2 5 4 6 7 8
我认为算法的分区部分存在问题,但我找不到它。
修改
我可能发现了一个问题和修改过的算法。现在我找不到任何反例,但如果有人看错了,请指出: - )
void quickSort(Node* left, Node* right) {
Node* start = left;
Node* cur = left;
T pivot = start->data;
if (left == right) return;
if (left->next == right) {
if (right->data < left->data) swap(left->data,right->data);
return;
}
swap(start->data,right->data);
while (cur != right->next) {
if (cur->data < pivot) {
swap(cur->data,start->data);
start = start->next;
}
cur = cur->next;
}
swap(right->data,start->data);
quickSort(left, start);
if (start->next != nullptr) quickSort(start->next, right);
}