From 962165d5d8a9e1172aa042079a4ab8f6d24afce1 Mon Sep 17 00:00:00 2001 From: huizixin Date: Fri, 12 Jun 2026 15:08:49 +0800 Subject: [PATCH] fix: handle zero and negative numbers in RadixSort getLengthOfLongestElement Math.log10(0) returns -Infinity and Math.log10(-N) returns NaN, causing the sorting loop to never execute for arrays containing only zeros or negative numbers. Added early return for edge cases where max value is 0 or negative. --- src/algorithms/sorting/radix-sort/RadixSort.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/algorithms/sorting/radix-sort/RadixSort.js b/src/algorithms/sorting/radix-sort/RadixSort.js index 8e8dccfb0d..3da15514ac 100644 --- a/src/algorithms/sorting/radix-sort/RadixSort.js +++ b/src/algorithms/sorting/radix-sort/RadixSort.js @@ -113,7 +113,10 @@ export default class RadixSort extends Sort { */ getLengthOfLongestElement(array) { if (this.isArrayOfNumbers(array)) { - return Math.floor(Math.log10(Math.max(...array))) + 1; + const max = Math.max(...array); + // Handle edge cases where max is 0 or negative + if (max <= 0) return 1; + return Math.floor(Math.log10(max)) + 1; } return array.reduce((acc, val) => {