diff --git a/src/lib/sort.rs b/src/lib/sort.rs index 9154d6a823a47..b14c0cf2b0ec7 100644 --- a/src/lib/sort.rs +++ b/src/lib/sort.rs @@ -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); } } diff --git a/src/test/run-pass/simple-qsort.rs b/src/test/run-pass/simple-qsort.rs new file mode 100644 index 0000000000000..7f237870c5a33 --- /dev/null +++ b/src/test/run-pass/simple-qsort.rs @@ -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(); +}