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.

Revisions

  1. GargoyleLizy created this gist Feb 15, 2019.
    21 changes: 21 additions & 0 deletions CountingSort.kt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,21 @@
    /**
    * 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
    }
    }