Last active
February 27, 2020 11:38
-
-
Save igodorogea/8fc1cef78690a7d03f49b1b488db5daf to your computer and use it in GitHub Desktop.
Counting Sort
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
// https://www.youtube.com/watch?v=OKd534EWcdk | |
countingSort([1,4,1,2,7,5,30,8,2]); | |
function countingSort(arr) { | |
const positions = calculatePositions(arr); | |
const sortedArr = [] | |
for (let i = 0; i < arr.length; i++) { | |
sortedArr[positions[arr[i]]] = arr[i] | |
positions[arr[i]] += 1 | |
} | |
return sortedArr | |
} | |
function calculatePositions(arr) { | |
const positions = [] | |
for (let i = 0; i < arr.length; i++) { | |
positions[arr[i]] = (positions[arr[i]] || 0) + 1 | |
} | |
for (let i = 0; i < positions.length; i++) { | |
positions[i] = (positions[i] || 0) + (positions[i-1] || 0) | |
} | |
positions.pop() | |
positions.unshift(0) | |
return positions | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment