mirror of
https://github.com/krahets/hello-algo.git
synced 2024-12-25 00:26:29 +08:00
Fix panic when array's len is less than 2 (#1353)
This commit is contained in:
parent
1f606d6852
commit
7a96f6a743
1 changed files with 2 additions and 2 deletions
|
@ -35,11 +35,11 @@ fn sift_down(nums: &mut [i32], n: usize, mut i: usize) {
|
||||||
/* 堆排序 */
|
/* 堆排序 */
|
||||||
fn heap_sort(nums: &mut [i32]) {
|
fn heap_sort(nums: &mut [i32]) {
|
||||||
// 建堆操作:堆化除叶节点以外的其他所有节点
|
// 建堆操作:堆化除叶节点以外的其他所有节点
|
||||||
for i in (0..=nums.len() / 2 - 1).rev() {
|
for i in (0..nums.len() / 2).rev() {
|
||||||
sift_down(nums, nums.len(), i);
|
sift_down(nums, nums.len(), i);
|
||||||
}
|
}
|
||||||
// 从堆中提取最大元素,循环 n-1 轮
|
// 从堆中提取最大元素,循环 n-1 轮
|
||||||
for i in (1..=nums.len() - 1).rev() {
|
for i in (1..nums.len()).rev() {
|
||||||
// 交换根节点与最右叶节点(交换首元素与尾元素)
|
// 交换根节点与最右叶节点(交换首元素与尾元素)
|
||||||
let tmp = nums[0];
|
let tmp = nums[0];
|
||||||
nums[0] = nums[i];
|
nums[0] = nums[i];
|
||||||
|
|
Loading…
Reference in a new issue