File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed
Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change 1+ fun counting_sort(A: Array<Int>, max: Int) {
2+ // Array in which result will store
3+ var B = Array<Int>(A.size, { 0 })
4+ // count array
5+ var C = Array<Int>(max, { 0 })
6+ for (i in 0..A.size - 1) {
7+ //count the no. of occurrence of a
8+ //particular element store in count array
9+ C[A[i] - 1] = C[A[i] - 1] + 1
10+ }
11+ for (i in 1..C.size - 1) {
12+ // calculate commutative sum
13+ C[i] = C[i] + C[i - 1]
14+ }
15+ for (i in A.size - 1 downTo 0) {
16+ // place the element at its position
17+ B[C[A[i] - 1] - 1] = A[i]
18+ // decrease the occurrence of the element by 1
19+ C[A[i] - 1] = C[A[i] - 1] - 1
20+ }
21+ println("After sorting :")
22+ for (i in B) {
23+ print("$i ")
24+ }
25+
26+ }
27+
28+ fun main(arg: Array<String>) {
29+ print("Enter no. of elements :")
30+ var n = readLine()!!.toInt()
31+
32+ println("Enter elements : ")
33+ var A = Array(n, { 0 })
34+ for (i in 0 until n)
35+ A[i] = readLine()!!.toInt()
36+ // calculate maximum element from array
37+ var max = A[0];
38+ for (i in A) {
39+ if (i > max) {
40+ max = i
41+ }
42+ }
43+ counting_sort(A, max)
44+ }
You can’t perform that action at this time.
0 commit comments