In this article, we will write an insertion sort algorithm program in Kotlin. Below is the complexity comparison of insertion sort.
Best-case performance: O(n) comparisons, O(1) swaps
Average performance: О(n2) comparisons, swaps
Worst-case space complexity: О(n) total, O(1) auxiliary
Source Code:
Best-case performance: O(n) comparisons, O(1) swaps
Average performance: О(n2) comparisons, swaps
Worst-case space complexity: О(n) total, O(1) auxiliary
Source Code:
fun main(arg: Array<String>)
{
try
{
print("Enter size of array : ")
var n = readLine()!!.toInt()
println("Enter elements : ")
var A = Array(n, { 0 })
for (i in 0 until n) {
A[i] = readLine()!!.toInt()
}
insertion_sort(A,A.size)
println("Sorted array is : ")
for (i in 0 until n){
print("${A[i]} ")
}
}
catch(e: Exception)
{
print("$e")
}
}
/* Function to sort an array using insertion sort*/
fun insertion_sort(A: Array<Int>, n : Int)
{
var n = A.size
var i: Int
for (j in 1 until n)
{
var key = A[j]
i = j - 1
while (i >= 0 && A[i] > key) {
A[i + 1] = A[i]
i--
}
A[i + 1] = key
}
}
Output:{
try
{
print("Enter size of array : ")
var n = readLine()!!.toInt()
println("Enter elements : ")
var A = Array(n, { 0 })
for (i in 0 until n) {
A[i] = readLine()!!.toInt()
}
insertion_sort(A,A.size)
println("Sorted array is : ")
for (i in 0 until n){
print("${A[i]} ")
}
}
catch(e: Exception)
{
print("$e")
}
}
/* Function to sort an array using insertion sort*/
fun insertion_sort(A: Array<Int>, n : Int)
{
var n = A.size
var i: Int
for (j in 1 until n)
{
var key = A[j]
i = j - 1
while (i >= 0 && A[i] > key) {
A[i + 1] = A[i]
i--
}
A[i + 1] = key
}
}
Enter size of array : 5
Enter elements :
12
10
14
18
16
Sorted array is :
10 12 14 16 18
Description:Enter elements :
12
10
14
18
16
Sorted array is :
10 12 14 16 18
Insertion Sort Algorithm Program in Kotlin - Output |
In this program, we will take the size of an array from the end user. Next, it will ask to enter the number of elements of array. It will be stored in array A[i] = readLine()!!.toInt() using for loop. At this point elements of an array are not in sorted sequence.
Next, we have called the function fun insertion_sort(A: Array<Int>, n : Int), which accepts an array to be sorted and size of an array. A sorted array will be printed using print() function. More in this, we have used try{} catch{} blocks to validate user input.
Next, we have called the function fun insertion_sort(A: Array<Int>, n : Int), which accepts an array to be sorted and size of an array. A sorted array will be printed using print() function. More in this, we have used try{} catch{} blocks to validate user input.
0 Comments