Skip to content

Instantly share code, notes, and snippets.

@GargoyleLizy
Created February 15, 2019 11:19
Show Gist options
  • Save GargoyleLizy/2b173669bceb47c25d8484e02c550686 to your computer and use it in GitHub Desktop.
Save GargoyleLizy/2b173669bceb47c25d8484e02c550686 to your computer and use it in GitHub Desktop.
CountingSort
/**
* Counting Sort assumes every element of input array was inside [0,k]
*/
object CountingSort {
fun sort(input: Array<Int>, upperLimit: Int): Array<Int> {
val C = IntArray(upperLimit + 1) { 0 }
val output = Array<Int>(input.size) { 0 }
input.forEach { element ->
C[element]++
}
for (i in 1..upperLimit) {
C[i] = C[i] + C[i - 1]
}
for (i in output.size - 1 downTo 0) {
output[C[input[i]]-1] = input[i]
C[input[i]]--
}
return output
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment