From 72b1f0589763f3c1926dfdd272b060c8522aa385 Mon Sep 17 00:00:00 2001 From: Chaiwon Park Date: Fri, 28 Oct 2022 13:22:44 +0200 Subject: [PATCH] radix sort algorithm and basic test added --- src/main/kotlin/sort/RadixSort.kt | 45 +++++++++++++++++++++++++++ src/test/kotlin/sort/RadixSortTest.kt | 20 ++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 src/main/kotlin/sort/RadixSort.kt create mode 100644 src/test/kotlin/sort/RadixSortTest.kt diff --git a/src/main/kotlin/sort/RadixSort.kt b/src/main/kotlin/sort/RadixSort.kt new file mode 100644 index 0000000..65812c6 --- /dev/null +++ b/src/main/kotlin/sort/RadixSort.kt @@ -0,0 +1,45 @@ +package sort + +fun radixSort(array: Array, 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, n: Int, exp: Int) { + val output: MutableList = 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, n: Int): Int { + var max = array[0] + for (i in 1 until n) { + if (array[i] > max) { + max = array[i] + } + } + return max +} diff --git a/src/test/kotlin/sort/RadixSortTest.kt b/src/test/kotlin/sort/RadixSortTest.kt new file mode 100644 index 0000000..dc2a50e --- /dev/null +++ b/src/test/kotlin/sort/RadixSortTest.kt @@ -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]) + } + } +}