Fix qsort to not skip the right side when the pivot element gets put at index 0.

Closes #705.
This commit is contained in:
Michael Sullivan 2011-07-18 15:01:47 -07:00
parent ad1c0e6308
commit 71909a64bc
2 changed files with 31 additions and 4 deletions

View File

@ -63,8 +63,10 @@ fn qsort[T](lteq[T] compare_func, vec[mutable T] arr, uint left, uint right) {
if (right > left) {
auto pivot = (left + right) / 2u;
auto new_pivot = part[T](compare_func, arr, left, right, pivot);
if (new_pivot == 0u) { ret; }
qsort[T](compare_func, arr, left, new_pivot - 1u);
if (new_pivot != 0u) {
// Need to do this check before recursing due to overflow
qsort[T](compare_func, arr, left, new_pivot - 1u);
}
qsort[T](compare_func, arr, new_pivot + 1u, right);
}
}
@ -194,8 +196,10 @@ mod ivector {
if (right > left) {
auto pivot = (left + right) / 2u;
auto new_pivot = part[T](compare_func, arr, left, right, pivot);
if (new_pivot == 0u) { ret; }
qsort[T](compare_func, arr, left, new_pivot - 1u);
if (new_pivot != 0u) {
// Need to do this check before recursing due to overflow
qsort[T](compare_func, arr, left, new_pivot - 1u);
}
qsort[T](compare_func, arr, new_pivot + 1u, right);
}
}

View File

@ -0,0 +1,23 @@
use std;
import std::ivec;
import std::int;
import std::sort;
fn test_qsort() {
auto names = ~[mutable 2, 1, 3];
auto expected = ~[1, 2, 3];
fn lteq(&int a, &int b) -> bool { int::le(a, b) }
sort::ivector::quick_sort(lteq, names);
auto pairs = ivec::zip(expected, ivec::from_mut(names));
for (tup(int, int) p in pairs) {
log_err #fmt("%d %d", p._0, p._1);
assert p._0 == p._1;
}
}
fn main() {
test_qsort();
}