Skip to content

Commit 864ef42

Browse files
authored
fixed small bug in quick select algorithm (#727)
1 parent 717c266 commit 864ef42

File tree

1 file changed

+4
-4
lines changed

1 file changed

+4
-4
lines changed

src/searching/quick_select.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,13 @@ fn partition(list: &mut [i32], left: usize, right: usize, pivot_index: usize) ->
44
let pivot_value = list[pivot_index];
55
list.swap(pivot_index, right); // Move pivot to end
66
let mut store_index = left;
7-
for i in left..(right + 1) {
7+
for i in left..right {
88
if list[i] < pivot_value {
99
list.swap(store_index, i);
1010
store_index += 1;
1111
}
12-
list.swap(right, store_index); // Move pivot to its final place
1312
}
13+
list.swap(right, store_index); // Move pivot to its final place
1414
store_index
1515
}
1616

@@ -19,7 +19,7 @@ pub fn quick_select(list: &mut [i32], left: usize, right: usize, index: usize) -
1919
// If the list contains only one element,
2020
return list[left];
2121
} // return that element
22-
let mut pivot_index = 1 + left + (right - left) / 2; // select a pivotIndex between left and right
22+
let mut pivot_index = left + (right - left) / 2; // select a pivotIndex between left and right
2323
pivot_index = partition(list, left, right, pivot_index);
2424
// The pivot is in its final sorted position
2525
match index {
@@ -37,7 +37,7 @@ mod tests {
3737
let mut arr1 = [2, 3, 4, 5];
3838
assert_eq!(quick_select(&mut arr1, 0, 3, 1), 3);
3939
let mut arr2 = [2, 5, 9, 12, 16];
40-
assert_eq!(quick_select(&mut arr2, 1, 3, 2), 12);
40+
assert_eq!(quick_select(&mut arr2, 1, 3, 2), 9);
4141
let mut arr2 = [0, 3, 8];
4242
assert_eq!(quick_select(&mut arr2, 0, 0, 0), 0);
4343
}

0 commit comments

Comments
 (0)