mirror of
https://github.com/krahets/hello-algo.git
synced 2025-11-02 12:58:42 +08:00
Fix some codes and a figure.
This commit is contained in:
@ -5,7 +5,7 @@
|
||||
*/
|
||||
|
||||
/* 堆的长度为 n ,从节点 i 开始,从顶至底堆化 */
|
||||
function sift_down(nums, n, i) {
|
||||
function siftDown(nums, n, i) {
|
||||
while (true) {
|
||||
// 判断节点 i, l, r 中值最大的节点,记为 ma
|
||||
let l = 2 * i + 1;
|
||||
@ -29,21 +29,21 @@ function sift_down(nums, n, i) {
|
||||
}
|
||||
|
||||
/* 堆排序 */
|
||||
function heap_sort(nums) {
|
||||
function heapSort(nums) {
|
||||
// 建堆操作:堆化除叶节点以外的其他所有节点
|
||||
for (let i = Math.floor(nums.length / 2) - 1; i >= 0; i--) {
|
||||
sift_down(nums, nums.length, i);
|
||||
siftDown(nums, nums.length, i);
|
||||
}
|
||||
// 从堆中提取最大元素,循环 n-1 轮
|
||||
for (let i = nums.length - 1; i > 0; i--) {
|
||||
// 交换根节点与最右叶节点(即交换首元素与尾元素)
|
||||
[nums[0], nums[i]] = [nums[i], nums[0]];
|
||||
// 以根节点为起点,从顶至底进行堆化
|
||||
sift_down(nums, i, 0);
|
||||
siftDown(nums, i, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const nums = [4, 1, 3, 1, 5, 2];
|
||||
heap_sort(nums);
|
||||
console.log("堆排序完成后 nums =", nums);
|
||||
heapSort(nums);
|
||||
console.log('堆排序完成后 nums =', nums);
|
||||
|
||||
@ -5,7 +5,7 @@
|
||||
*/
|
||||
|
||||
/* 选择排序 */
|
||||
function selection_sort(nums) {
|
||||
function selectionSort(nums) {
|
||||
let n = nums.length;
|
||||
// 外循环:未排序区间为 [i, n-1]
|
||||
for (let i = 0; i < n - 1; i++) {
|
||||
@ -13,7 +13,7 @@ function selection_sort(nums) {
|
||||
let k = i;
|
||||
for (let j = i + 1; j < n; j++) {
|
||||
if (nums[j] < nums[k]) {
|
||||
k = j; // 记录最小元素的索引
|
||||
k = j; // 记录最小元素的索引
|
||||
}
|
||||
}
|
||||
// 将该最小元素与未排序区间的首个元素交换
|
||||
@ -23,5 +23,5 @@ function selection_sort(nums) {
|
||||
|
||||
/* Driver Code */
|
||||
const nums = [4, 1, 3, 1, 5, 2];
|
||||
selection_sort(nums);
|
||||
console.log("选择排序完成后 nums =", nums);
|
||||
selectionSort(nums);
|
||||
console.log('选择排序完成后 nums =', nums);
|
||||
|
||||
Reference in New Issue
Block a user