# Sorting in linear time and program for Count Sort in Kotlin

In this article, we are going to learn how to implement Count Sort in Kotlin? Here you will find its algorithm and program in Kotlin.
Submitted by Aman Gautam, on December 23, 2017

Till now we have studied the sorting algorithms which take O(nlogn) (Merge, heap, quick sort) time to O(n2 ) (Bubble, Insertion, Selection sort) time . All these were comparison sort but there are some other sorting Algorithms which use operations other than comparison to determine the sorted order and can sort the elements in O(n) time i.e. in linear time.

The sorting algorithms which can sort the elements in linear time are,

1. Count sort
2. Bucket sort

Read More: counting sort (explanation, example and program in C++)

Here are few assumptions before using counting sort,

1. There should be no negative number.
2. All the elements are in order of 0 to max (max element from list) and max=O(n)

Algorithm

```	COUNTING_SORT(A,max)
1.	Let C[0..max] be a new array
2.	Let B[0..A.length] be a new array
3.	for i=0 to max
4.	    C[A[i]] = C[A[i]] + 1
5.	for i=1..C.length- 1
6.	    C[i] = C[i] + C[i– 1]
7.	for i=A.length downTo 0
8.	B[C[A[i] ]] = A[i]
9.	C[A[i] ] = C[A[i] ] - 1
10.	    Print B[ ] as sorted array
```

Algorithm source from Introduction to Algorithms by CLRC

Complexity -> O(n)

## Program for counting sort in Kotlin

```fun counting_sort(A: Array<Int>, max: Int) {
// Array in which result will store
var B = Array<Int>(A.size, { 0 })
// count array
var C = Array<Int>(max, { 0 })
for (i in 0..A.size - 1) {
//count the no. of occurrence of a
//particular element store in count array
C[A[i] - 1] = C[A[i] - 1] + 1
}
for (i in 1..C.size - 1) {
// calculate commutative sum
C[i] = C[i] + C[i - 1]
}
for (i in A.size - 1 downTo 0) {
// place the element at its position
B[C[A[i] - 1] - 1] = A[i]
// decrease the occurrence of the element by 1
C[A[i] - 1] = C[A[i] - 1] - 1
}
println("After sorting :")
for (i in B) {
print("\$i ")
}

}

fun main(arg: Array<String>) {
print("Enter no. of elements :")

println("Enter elements : ")
var A = Array(n, { 0 })
for (i in 0 until n)
// calculate maximum element from array
var max = A[0];
for (i in A) {
if (i > max) {
max = i
}
}
counting_sort(A, max)
}
```

Output

```Enter no. of elements :10
Enter elements :
5
4
3
7
9
4
3
5
7
1
After sorting :
1 3 3 4 4 5 5 7 7 9
```

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates