Created
January 27, 2022 02:26
-
-
Save kevinjie/0ea11a134bbd9dddcf6fcd747c5bcc3a to your computer and use it in GitHub Desktop.
countingSort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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