Answers for "javascript counting sort"

1

javascript counting sort

const countingSort = arr => {
  const min = arr.reduce((acc, v) => (acc < v ? acc : v))
  const max = arr.reduce((acc, v) => (acc > v ? acc : v))
  const count = new Map()

  for (let i = min; i <= max; i++) {
    count[i] = 0
  }
  for (let i = 0; i < arr.length; i++) {
    count[arr[i]] += 1
  }

  const sortedArr = []
  for (let i = min; i <= max; i++) {
    while (count[i] > 0) {
      sortedArr.push(i)
      count[i]--
    }
  }
  return sortedArr
}
Posted by: Guest on April-16-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language