Skip to content

Commit 962165d

Browse files
committed
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.
1 parent 3b53377 commit 962165d

1 file changed

Lines changed: 4 additions & 1 deletion

File tree

src/algorithms/sorting/radix-sort/RadixSort.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,10 @@ export default class RadixSort extends Sort {
113113
*/
114114
getLengthOfLongestElement(array) {
115115
if (this.isArrayOfNumbers(array)) {
116-
return Math.floor(Math.log10(Math.max(...array))) + 1;
116+
const max = Math.max(...array);
117+
// Handle edge cases where max is 0 or negative
118+
if (max <= 0) return 1;
119+
return Math.floor(Math.log10(max)) + 1;
117120
}
118121

119122
return array.reduce((acc, val) => {

0 commit comments

Comments
 (0)