Skip to content

Commit

Permalink
fixed small bug in quick select algorithm (TheAlgorithms#727)
Browse files Browse the repository at this point in the history
  • Loading branch information
BenjiAndre committed Jun 13, 2024
1 parent 717c266 commit 864ef42
Showing 1 changed file with 4 additions and 4 deletions.
8 changes: 4 additions & 4 deletions src/searching/quick_select.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ fn partition(list: &mut [i32], left: usize, right: usize, pivot_index: usize) ->
let pivot_value = list[pivot_index];
list.swap(pivot_index, right); // Move pivot to end
let mut store_index = left;
for i in left..(right + 1) {
for i in left..right {
if list[i] < pivot_value {
list.swap(store_index, i);
store_index += 1;
}
list.swap(right, store_index); // Move pivot to its final place
}
list.swap(right, store_index); // Move pivot to its final place
store_index
}

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

0 comments on commit 864ef42

Please sign in to comment.