Fix qsort to not skip the right side when the pivot element gets put at index 0.
Closes #705.
This commit is contained in:
parent
ad1c0e6308
commit
71909a64bc
@ -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);
|
||||
}
|
||||
}
|
||||
|
23
src/test/run-pass/simple-qsort.rs
Normal file
23
src/test/run-pass/simple-qsort.rs
Normal 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();
|
||||
}
|
Loading…
Reference in New Issue
Block a user