Skip to content

Commit 4902212

Browse files
author
Jarvis@LNMIIT
committed
Adding Counting Sort in Scala
1 parent baad0c4 commit 4902212

2 files changed

Lines changed: 25 additions & 0 deletions

File tree

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
2+
class CountingSort {
3+
4+
def countSort(listToBeSorted: List[Int], minValue: Int, maxValue: Int): List[Int] =
5+
6+
listToBeSorted.foldLeft(Array.fill(maxValue - minValue + 1)(0)) { (arr, n) =>
7+
arr(n - minValue) += 1
8+
arr
9+
}.zipWithIndex.foldLeft(List[Int]()) {
10+
case (lst, (cnt, ndx)) => List.fill(cnt)(ndx + minValue) ::: lst
11+
}.reverse
12+
}
13+
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import org.scalatest.{Matchers, FunSuite}
2+
3+
class CountingSortTest extends FunSuite with Matchers {
4+
5+
test("generateCountList should generate") {
6+
val objectForCountingSort = new CountingSort
7+
8+
objectForCountingSort.countSort(List(11,1,22,33,23),1,33) should be(List(1,11,22,23,33))
9+
objectForCountingSort.countSort(List(1,2,3,4,5,6,7,8,9),1,9) should be(List(1,2,3,4,5,6,7,8,9))
10+
}
11+
}
12+

0 commit comments

Comments
 (0)