Skip to content

Commit 71909a6

Browse files
committed
Fix qsort to not skip the right side when the pivot element gets put at index 0.
Closes #705.
1 parent ad1c0e6 commit 71909a6

File tree

2 files changed

+31
-4
lines changed

2 files changed

+31
-4
lines changed

src/lib/sort.rs

+8-4
Original file line numberDiff line numberDiff line change
@@ -63,8 +63,10 @@ fn qsort[T](lteq[T] compare_func, vec[mutable T] arr, uint left, uint right) {
6363
if (right > left) {
6464
auto pivot = (left + right) / 2u;
6565
auto new_pivot = part[T](compare_func, arr, left, right, pivot);
66-
if (new_pivot == 0u) { ret; }
67-
qsort[T](compare_func, arr, left, new_pivot - 1u);
66+
if (new_pivot != 0u) {
67+
// Need to do this check before recursing due to overflow
68+
qsort[T](compare_func, arr, left, new_pivot - 1u);
69+
}
6870
qsort[T](compare_func, arr, new_pivot + 1u, right);
6971
}
7072
}
@@ -194,8 +196,10 @@ mod ivector {
194196
if (right > left) {
195197
auto pivot = (left + right) / 2u;
196198
auto new_pivot = part[T](compare_func, arr, left, right, pivot);
197-
if (new_pivot == 0u) { ret; }
198-
qsort[T](compare_func, arr, left, new_pivot - 1u);
199+
if (new_pivot != 0u) {
200+
// Need to do this check before recursing due to overflow
201+
qsort[T](compare_func, arr, left, new_pivot - 1u);
202+
}
199203
qsort[T](compare_func, arr, new_pivot + 1u, right);
200204
}
201205
}

src/test/run-pass/simple-qsort.rs

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
use std;
2+
import std::ivec;
3+
import std::int;
4+
import std::sort;
5+
6+
fn test_qsort() {
7+
auto names = ~[mutable 2, 1, 3];
8+
9+
auto expected = ~[1, 2, 3];
10+
11+
fn lteq(&int a, &int b) -> bool { int::le(a, b) }
12+
sort::ivector::quick_sort(lteq, names);
13+
14+
auto pairs = ivec::zip(expected, ivec::from_mut(names));
15+
for (tup(int, int) p in pairs) {
16+
log_err #fmt("%d %d", p._0, p._1);
17+
assert p._0 == p._1;
18+
}
19+
}
20+
21+
fn main() {
22+
test_qsort();
23+
}

0 commit comments

Comments
 (0)