Skip to content

Instantly share code, notes, and snippets.

@kevinjie
Created January 27, 2022 02:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevinjie/0ea11a134bbd9dddcf6fcd747c5bcc3a to your computer and use it in GitHub Desktop.
Save kevinjie/0ea11a134bbd9dddcf6fcd747c5bcc3a to your computer and use it in GitHub Desktop.
countingSort
function sort(originalArray) {
const array = [...originalArray]
let biggestElement = array[0]
let smallestElement = array[0]
array.forEach((element) => {
if (element > biggestElement) {
biggestElement = element
}
if (element < smallestElement) {
smallestElement = element
}
})
const count = Array(biggestElement - smallestElement + 1).fill(0)
array.forEach((element) => {
count[element - smallestElement] += 1
})
for(let i = 1; i < count.length; i += 1) {
count[i] += count[i - 1]
}
const sortedArray = Array(array.length).fill(null)
for(let i = 0; i < array.length; i += 1) {
const element = array[i]
sortedArray[count[element - smallestElement] - 1] = element
count[element - smallestElement] -= 1
}
return sortedArray
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment