Skip to content

fixed small bug in quick select algorithm #727

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 13, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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