javascript counting sort

Solutions on MaxInterview for javascript counting sort by the best coders in the world

showing results for - "javascript counting sort"
Sara
06 Jan 2021
1const countingSort = arr => {
2  const min = arr.reduce((acc, v) => (acc < v ? acc : v))
3  const max = arr.reduce((acc, v) => (acc > v ? acc : v))
4  const count = new Map()
5
6  for (let i = min; i <= max; i++) {
7    count[i] = 0
8  }
9  for (let i = 0; i < arr.length; i++) {
10    count[arr[i]] += 1
11  }
12
13  const sortedArr = []
14  for (let i = min; i <= max; i++) {
15    while (count[i] > 0) {
16      sortedArr.push(i)
17      count[i]--
18    }
19  }
20  return sortedArr
21}