Program for Selection sort in Kotlin

In this article, we are going to learn how to implement a selection sort in Kotlin? Here, you will find what is selection sort, its algorithm, program with the explanation?
Submitted by Aman Gautam, on December 13, 2017

In selection sort first, we find out a minimum or maximum element from the unsorted array then placed it into its appropriate position in the sorted array. If we select minimum element, then we have to swap it with the leftmost element or if we select maximum element then we have to swap it with the rightmost element.

Algorithm

    SELECTION-SORT(A)
    1.	for i=n-1 to 0
    2.	    max = i
    3.	    for j = 0 to i
    4.	        if ( A[j] > A[max]
    5.	            max=j
    6.	   swap A[i] with A[max]
    7.	end 

Algorithm source from Introduction to Algorithms 3rd Edition by cormen.

In this algorithm first, we check for the maximum element from an unsorted array and then swap it with the last index of the array. Similarly, we check for the second maximum element then place it on second last position and so on till the whole array gets sorted. This algorithm takes O(n2) time in worst case. This is not suitable for a large number of n i.e. number of elements.

Program

fun selection_sort(A:Array<Int>){
    var n=A.size
    var temp:Int
    for(i in n-1 downTo  0){
        var max = i
        for(j in 0 until i){
            if(A[j]>A[max])
                max=j
        }
        if(i!=max){
        temp =A[i]
        A[i]=A[max]
        A[max]=temp
       }
    }
}

fun main(arg: Array<String>) {
    print("Enter no. of elements :")
    var n = readLine()!!.toInt()

    println("Enter elements : ")
    var A = Array(n, { 0 })
    for (i in 0 until n)
        A[i] = readLine()!!.toInt()

    selection_sort(A)

    println("Sorted array is : ")
    for (i in 0 until n)
        print("${A[i]}  ")
}

Output

Enter no. of elements :5
Enter elements :
12
32
11
32
43
Sorted array is :
11  12  32  32  43  


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.