Skip to content

Commit

Permalink
Fix qsort to not skip the right side when the pivot element gets put …
Browse files Browse the repository at this point in the history
…at index 0.

Closes #705.
  • Loading branch information
msullivan committed Jul 18, 2011
1 parent ad1c0e6 commit 71909a6
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 4 deletions.
12 changes: 8 additions & 4 deletions src/lib/sort.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
Expand Down Expand Up @@ -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);
}
}
Expand Down
23 changes: 23 additions & 0 deletions src/test/run-pass/simple-qsort.rs
Original file line number Diff line number Diff line change
@@ -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();
}

0 comments on commit 71909a6

Please sign in to comment.