mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-05 00:01:37 +08:00
Fix bug in bucketSort so that a comparison function is now provided to the sort function
The [built-in JavaScript sort method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) will perform a lexicographical (aka alphabetical) order by converting the elements of the array to strings. This can yield unexpected results when sorting numbers. A comparison function can be passed into the sort method to indicate how array elements should be compared.
This commit is contained in:
@ -53,7 +53,7 @@ function bucketSort (list, size) {
|
||||
const sorted = []
|
||||
// now sort every bucket and merge it to the sorted list
|
||||
for (let iBucket = 0; iBucket < buckets.length; iBucket++) {
|
||||
const arr = buckets[iBucket].sort()
|
||||
const arr = buckets[iBucket].sort((a, b) => a - b)
|
||||
for (let iSorted = 0; iSorted < arr.length; iSorted++) {
|
||||
sorted.push(arr[iSorted])
|
||||
}
|
||||
|
Reference in New Issue
Block a user