0
0
KotlinProgramBeginner · 2 min read

Kotlin Program for Selection Sort with Example and Explanation

A Kotlin program for selection sort uses nested for loops to find the minimum element and swap it with the current position, like for (i in 0 until arr.size - 1) { var minIndex = i; for (j in i + 1 until arr.size) { if (arr[j] < arr[minIndex]) minIndex = j }; val temp = arr[minIndex]; arr[minIndex] = arr[i]; arr[i] = temp }.
📋

Examples

Input[5, 3, 8, 4, 2]
Output[2, 3, 4, 5, 8]
Input[1, 2, 3, 4, 5]
Output[1, 2, 3, 4, 5]
Input[9]
Output[9]
🧠

How to Think About It

To sort an array using selection sort, think of dividing the array into two parts: sorted and unsorted. Start from the first element, find the smallest element in the unsorted part, and swap it with the current element. Repeat this for each position until the whole array is sorted.
📐

Algorithm

1
Start from the first element of the array.
2
Find the smallest element in the unsorted part of the array.
3
Swap the smallest element with the current element.
4
Move to the next element and repeat until the end of the array.
💻

Code

kotlin
fun selectionSort(arr: IntArray) {
    for (i in 0 until arr.size - 1) {
        var minIndex = i
        for (j in i + 1 until arr.size) {
            if (arr[j] < arr[minIndex]) {
                minIndex = j
            }
        }
        if (minIndex != i) {
            val temp = arr[minIndex]
            arr[minIndex] = arr[i]
            arr[i] = temp
        }
    }
}

fun main() {
    val arr = intArrayOf(5, 3, 8, 4, 2)
    selectionSort(arr)
    println(arr.joinToString(prefix = "[", postfix = "]", separator = ", "))
}
Output
[2, 3, 4, 5, 8]
🔍

Dry Run

Let's trace the array [5, 3, 8, 4, 2] through the selection sort code.

1

First outer loop (i=0)

Find minimum from index 0 to 4: minimum is 2 at index 4. Swap arr[0] and arr[4]. Array becomes [2, 3, 8, 4, 5].

2

Second outer loop (i=1)

Find minimum from index 1 to 4: minimum is 3 at index 1. Swap arr[1] and arr[1]. Array stays [2, 3, 8, 4, 5].

3

Third outer loop (i=2)

Find minimum from index 2 to 4: minimum is 4 at index 3. Swap arr[2] and arr[3]. Array becomes [2, 3, 4, 8, 5].

4

Fourth outer loop (i=3)

Find minimum from index 3 to 4: minimum is 5 at index 4. Swap arr[3] and arr[4]. Array becomes [2, 3, 4, 5, 8].

iminIndexArray state after swap
04[2, 3, 8, 4, 5]
11[2, 3, 8, 4, 5]
23[2, 3, 4, 8, 5]
34[2, 3, 4, 5, 8]
💡

Why This Works

Step 1: Finding the minimum element

The inner for loop scans the unsorted part of the array to find the smallest element by comparing each element with the current minimum.

Step 2: Swapping elements

After finding the minimum element, it swaps places with the element at the current position to move it into the sorted part.

Step 3: Repeating for all elements

The outer for loop moves the boundary of the sorted part forward until the entire array is sorted.

🔄

Alternative Approaches

Using Kotlin's built-in sort function
kotlin
fun main() {
    val arr = intArrayOf(5, 3, 8, 4, 2)
    arr.sort()
    println(arr.joinToString(prefix = "[", postfix = "]", separator = ", "))
}
This is the simplest and fastest way but does not teach the sorting logic.
Bubble Sort
kotlin
fun bubbleSort(arr: IntArray) {
    for (i in arr.indices) {
        for (j in 0 until arr.size - i - 1) {
            if (arr[j] > arr[j + 1]) {
                val temp = arr[j]
                arr[j] = arr[j + 1]
                arr[j + 1] = temp
            }
        }
    }
}

fun main() {
    val arr = intArrayOf(5, 3, 8, 4, 2)
    bubbleSort(arr)
    println(arr.joinToString(prefix = "[", postfix = "]", separator = ", "))
}
Bubble sort is easier to understand but usually slower than selection sort.

Complexity: O(n²) time, O(1) space

Time Complexity

Selection sort uses two nested loops each running up to n times, resulting in O(n²) time complexity regardless of input order.

Space Complexity

It sorts the array in place using only a few extra variables, so space complexity is O(1).

Which Approach is Fastest?

Built-in sort functions are fastest and optimized, while selection sort is simple but slower; bubble sort is generally slower than selection sort.

ApproachTimeSpaceBest For
Selection SortO(n²)O(1)Small arrays, learning sorting basics
Bubble SortO(n²)O(1)Simple logic, educational purposes
Built-in sortO(n log n)O(1) or O(n)Real-world use, large arrays
💡
Always swap only when you find a smaller element to reduce unnecessary operations.
⚠️
Beginners often forget to update the minimum index inside the inner loop, causing incorrect sorting.