Add JavaScript and TypeScript code of heap sort, selection sort and binary search edge and Fix the indentation of TS code (#545)

* Fix the indentation of TS code

* Add JavaScript and TypeScript code of heap sort, selection sort and binary search edge

* Fix the style of JS and TS code
This commit is contained in:
Justin Tse
2023-06-05 00:20:11 +08:00
committed by GitHub
parent 6377e3316a
commit 2532f06c7f
7 changed files with 273 additions and 9 deletions

View File

@ -0,0 +1,49 @@
/**
* File: heap_sort.js
* Created Time: 2023-06-04
* Author: Justin (xiefahit@gmail.com)
*/
/* 堆的长度为 n ,从节点 i 开始,从顶至底堆化 */
function sift_down(nums, n, i) {
while (true) {
// 判断节点 i, l, r 中值最大的节点,记为 ma
let l = 2 * i + 1;
let r = 2 * i + 2;
let ma = i;
if (l < n && nums[l] > nums[ma]) {
ma = l;
}
if (r < n && nums[r] > nums[ma]) {
ma = r;
}
// 若节点 i 最大或索引 l, r 越界,则无需继续堆化,跳出
if (ma === i) {
break;
}
// 交换两节点
[nums[i], nums[ma]] = [nums[ma], nums[i]];
// 循环向下堆化
i = ma;
}
}
/* 堆排序 */
function heap_sort(nums) {
// 建堆操作:堆化除叶节点以外的其他所有节点
for (let i = Math.floor(nums.length / 2) - 1; i >= 0; i--) {
sift_down(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);
}
}
/* Driver Code */
const nums = [4, 1, 3, 1, 5, 2];
heap_sort(nums);
console.log("堆排序完成后 nums =", nums);

View File

@ -0,0 +1,27 @@
/**
* File: selection_sort.js
* Created Time: 2023-06-04
* Author: Justin (xiefahit@gmail.com)
*/
/* 选择排序 */
function selection_sort(nums) {
let n = nums.length;
// 外循环:未排序区间为 [i, n-1]
for (let i = 0; i < n - 1; i++) {
// 内循环:找到未排序区间内的最小元素
let k = i;
for (let j = i + 1; j < n; j++) {
if (nums[j] < nums[k]) {
k = j; // 记录最小元素的索引
}
}
// 将该最小元素与未排序区间的首个元素交换
[nums[i], nums[k]] = [nums[k], nums[i]];
}
}
/* Driver Code */
const nums = [4, 1, 3, 1, 5, 2];
selection_sort(nums);
console.log("选择排序完成后 nums =", nums);