optimized the js api use of counting_sort chapter for Math.max() (#1748)

* Update counting_sort.ts optimized the Math.max

* Update counting_sort.ts

* Update counting_sort.js

* Update radix_sort.ts

* Update radix_sort.js
This commit is contained in:
Asashishi_Nyan!
2025-05-17 17:17:22 +08:00
committed by GitHub
parent e79a56f540
commit 09f7223067
4 changed files with 6 additions and 28 deletions

View File

@ -8,10 +8,7 @@
// 简单实现,无法用于排序对象
function countingSortNaive(nums) {
// 1. 统计数组最大元素 m
let m = 0;
for (const num of nums) {
m = Math.max(m, num);
}
let m = Math.max(...nums);
// 2. 统计各数字的出现次数
// counter[num] 代表 num 的出现次数
const counter = new Array(m + 1).fill(0);
@ -31,10 +28,7 @@ function countingSortNaive(nums) {
// 完整实现,可排序对象,并且是稳定排序
function countingSort(nums) {
// 1. 统计数组最大元素 m
let m = 0;
for (const num of nums) {
m = Math.max(m, num);
}
let m = Math.max(...nums);
// 2. 统计各数字的出现次数
// counter[num] 代表 num 的出现次数
const counter = new Array(m + 1).fill(0);

View File

@ -41,12 +41,7 @@ function countingSortDigit(nums, exp) {
/* 基数排序 */
function radixSort(nums) {
// 获取数组的最大元素,用于判断最大位数
let m = Number.MIN_VALUE;
for (const num of nums) {
if (num > m) {
m = num;
}
}
let m = Math.max(... nums);
// 按照从低位到高位的顺序遍历
for (let exp = 1; exp <= m; exp *= 10) {
// 对数组元素的第 k 位执行计数排序

View File

@ -8,10 +8,7 @@
// 简单实现,无法用于排序对象
function countingSortNaive(nums: number[]): void {
// 1. 统计数组最大元素 m
let m = 0;
for (const num of nums) {
m = Math.max(m, num);
}
let m: number = Math.max(...nums);
// 2. 统计各数字的出现次数
// counter[num] 代表 num 的出现次数
const counter: number[] = new Array<number>(m + 1).fill(0);
@ -31,10 +28,7 @@ function countingSortNaive(nums: number[]): void {
// 完整实现,可排序对象,并且是稳定排序
function countingSort(nums: number[]): void {
// 1. 统计数组最大元素 m
let m = 0;
for (const num of nums) {
m = Math.max(m, num);
}
let m: number = Math.max(...nums);
// 2. 统计各数字的出现次数
// counter[num] 代表 num 的出现次数
const counter: number[] = new Array<number>(m + 1).fill(0);

View File

@ -41,12 +41,7 @@ function countingSortDigit(nums: number[], exp: number): void {
/* 基数排序 */
function radixSort(nums: number[]): void {
// 获取数组的最大元素,用于判断最大位数
let m = Number.MIN_VALUE;
for (const num of nums) {
if (num > m) {
m = num;
}
}
let m: number = Math.max(... nums);
// 按照从低位到高位的顺序遍历
for (let exp = 1; exp <= m; exp *= 10) {
// 对数组元素的第 k 位执行计数排序