TheAlgorithms / Rust

All Algorithms implemented in Rust
MIT License
22.21k stars 2.17k forks source link

fixed small bug in quick select algorithm #727

Closed BenjiAndre closed 3 months ago

BenjiAndre commented 4 months ago

Pull Request Template

Description

This pull request fixes issue #714.

1. Fix partition Function

2. Adjust Pivot Selection in quick_select Function

3. Correct Test Case

Detailed Changes

  1. Partition Function:

    fn partition(list: &mut [i32], left: usize, right: usize, pivot_index: usize) -> 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 {
           if list[i] < pivot_value {
               list.swap(store_index, i);
               store_index += 1;
           }
       }
       list.swap(right, store_index); // Move pivot to its final place
       store_index
    }
  2. Quick Select Function:

    pub fn quick_select(list: &mut [i32], left: usize, right: usize, index: usize) -> i32 {
       if left == right {
           return list[left];
       }
       let mut pivot_index = left + (right - left) / 2; // select a pivotIndex between left and right
       pivot_index = partition(list, left, right, pivot_index);
       match index {
           x if x == pivot_index => list[index],
           x if x < pivot_index => quick_select(list, left, pivot_index - 1, index),
           _ => quick_select(list, pivot_index + 1, right, index),
       }
    }
  3. Test Case Correction:

    #[cfg(test)]
    mod tests {
       use super::*;
       #[test]
       fn it_works() {
           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), 9); // Corrected to 9
           let mut arr3 = [0, 3, 8];
           assert_eq!(quick_select(&mut arr3, 0, 0, 0), 0);
       }
    }

These changes ensure the Quickselect algorithm functions correctly and the test cases produce the expected results.

Type of change

Please delete options that are not relevant.

Checklist:

codecov-commenter commented 4 months ago

Codecov Report

All modified and coverable lines are covered by tests :white_check_mark:

Project coverage is 95.00%. Comparing base (0cc792c) to head (5ec1c09).

Additional details and impacted files ```diff @@ Coverage Diff @@ ## master #727 +/- ## ========================================== - Coverage 95.01% 95.00% -0.01% ========================================== Files 303 303 Lines 22522 22522 ========================================== - Hits 21399 21398 -1 - Misses 1123 1124 +1 ```

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.