Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions src/main/kotlin/sort/RadixSort.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package sort

fun radixSort(array: Array<Int>, n: Int) {
val m = getMax(array, n)

var exp = 1
while (m / exp > 0) {
countSort(array, n, exp)
exp *= 10
}
}

private fun countSort(array: Array<Int>, n: Int, exp: Int) {
val output: MutableList<Int?> = mutableListOf(*arrayOfNulls(n))
val count = MutableList(10) { 0 }

for (i in 0 until n) {
count[(array[i].div(exp)) % 10]++
}

for (i in 1 until 10) {
count[i] += count[i - 1]
}

var i: Int = n - 1
while (i >= 0) {
output[count[array[i] / exp % 10] - 1] = array[i]
count[array[i] / exp % 10]--
i--
}

for (i in 0 until n) {
array[i] = output[i]!!
}
}

private fun getMax(array: Array<Int>, n: Int): Int {
var max = array[0]
for (i in 1 until n) {
if (array[i] > max) {
max = array[i]
}
}
return max
}
20 changes: 20 additions & 0 deletions src/test/kotlin/sort/RadixSortTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package sort

import org.junit.Assert.assertEquals
import org.junit.Test

class RadixSortTest {

@Test
fun `basicTest`() {
val input = arrayOf(170, 45, 75, 90, 802, 24, 2, 66)
val n = input.size

val expected = arrayOf(2, 24, 45, 66, 75, 90, 170, 802)
radixSort(input, n)

for (i in 0 until n) {
assertEquals(expected[i], input[i])
}
}
}