fork download
  1. fun countOccurrences(array: MutableList<Int>, maxNumber: Int): Array<Int> {
  2. val occurrences = Array<Int>(maxNumber + 1){0}
  3.  
  4. for (number in array) {
  5. occurrences[number]++
  6. }
  7.  
  8. return occurrences
  9. }
  10.  
  11.  
  12. fun countingSort(array: MutableList<Int>) {
  13. val occurrences = countOccurrences(array, 100)
  14. var index = 0
  15.  
  16. for (i in occurrences.indices) {
  17. for (j in 1..occurrences[i]) {
  18. array[index] = i
  19. index++
  20. }
  21. }
  22. }
  23.  
  24. fun main() {
  25. val array = mutableListOf(7, 3, 0, 1, 5, 2, 5, 19, 10, 5)
  26.  
  27. countingSort(array)
  28.  
  29. println(array)
  30. }
Success #stdin #stdout 0.1s 39492KB
stdin
Standard input is empty
stdout
[0, 1, 2, 3, 5, 5, 5, 7, 10, 19]