Skip to content

Commit

Permalink
Add documentation for quick sort partition function
Browse files Browse the repository at this point in the history
  • Loading branch information
DaviRain-Su committed Jun 15, 2023
1 parent 8501667 commit 3b3602d
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions rust/src/sort/quick_sort.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,29 @@ pub fn partition<T: Ord + std::fmt::Debug>(arr: &mut [T]) -> usize {
i
}

/// 当然可以,我来给你解释一下。
///
/// 我们使用一个整数数组作为例子: `[9, 7, 5, 11, 12, 2, 14, 3, 10, 6]`
///
/// 1. 在我们的 `partition` 函数中,`pivot` 是最后一个元素,所以 `pivot` = 6。
///
/// 2. 初始化 `i = 0`,这是一个“指针”,它指向我们要交换的下一个元素。
///
/// 3. 我们遍历数组中除 `pivot` 的其他元素。对于每个元素 `j`,如果 `arr[j] <= pivot`,
/// 那么我们就交换 `arr[i]` 和 `arr[j]`,然后 `i` 自增 1。这样做的目的是将所有小于或等于 `pivot` 的元素移动到数组的左侧。
///
/// 4. 当我们完成遍历时,`arr` 可能看起来像这样:`[5, 2, 3, 11, 12, 9, 14, 7, 10, 6]`。
/// 现在,`i = 3`,也就是 `arr[i] = 11`。注意到所有小于等于 `pivot`(6)的元素都在左侧,而所有大于 `pivot` 的元素都在右侧。但是,`pivot` 本身还在数组的最右侧。
///
/// 5. 我们将 `pivot` 与 `arr[i]` 交换,得到:`[5, 2, 3, 6, 12, 9, 14, 7, 10, 11]`。
/// 这样就确保了 `pivot` 的左侧都是小于或等于它的元素,右侧都是大于它的元素。
///
/// 6. 最后,`partition` 函数返回 `pivot` 的位置,也就是 `i` 的值,它是 3。
///
/// 在 `quickify` 函数中,我们会对 `pivot` 左侧的元素(索引 `0` 到 `pivot - 1`,
/// 即 `[5, 2, 3]`)和右侧的元素(索引 `pivot + 1` 到 `n - 1`,即 `[12, 9, 14, 7, 10, 11]`)进行递归排序。
/// 这样,在几轮递归后,整个数组就会被完全排序。

#[test]
fn test_quickify() {
let mut arr = [1, 3, 2, 5, 4, 7, 9, 8, 6];
Expand Down

0 comments on commit 3b3602d

Please sign in to comment.