Kotlin Program to Implement Selection Sort

Kotlin Program to Implement Selection Sort

Sorting is one of the most important concepts in programming, and learning it well helps you understand how data can be arranged and managed efficiently. One of the simplest sorting techniques is Selection Sort. It’s easy to understand, easy to implement, and forms a great foundation for learning other sorting algorithms. Selection Sort works by repeatedly finding the smallest (or largest) element from the unsorted part of an array and moving it to its correct position.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

This algorithm is often taught to beginners because it clearly shows how comparison and swapping work together to create a sorted list. While Selection Sort is not the fastest method for large datasets, it is an excellent way to grasp the basics of sorting. You will often find it used in small applications, simple data processing tasks, and educational examples. In this article, we will explore how to implement Selection Sort in Kotlin using different methods such as loops and recursion, and even look at a version that sorts in descending order.

Program 1: Basic Selection Sort using Loops

This is the simplest and most direct way to implement Selection Sort. It uses two loops to repeatedly find the smallest element and swap it into its correct place.

fun main() {

    val numbers = intArrayOf(64, 25, 12, 22, 11)

    println("Original Array: ${numbers.joinToString()}")

    for (i in numbers.indices) {

        var minIndex = i

        for (j in i + 1 until numbers.size) {

            if (numbers[j] < numbers[minIndex]) {
                minIndex = j
            }

        }

        val temp = numbers[i]
        numbers[i] = numbers[minIndex]
        numbers[minIndex] = temp

    }

    println("Sorted Array: ${numbers.joinToString()}")

}

In this program, the outer loop goes through each position in the array, while the inner loop finds the smallest element from the remaining unsorted part. Once the smallest element is found, it swaps places with the element at the current index. By the end of the process, all elements are arranged in ascending order. This approach is great for beginners to understand how sorting logic works through direct comparison and swapping.

Program 2: Optimized Selection Sort

This version adds a small optimization by checking if any swaps are needed at all. If the element is already in the right place, it avoids unnecessary swapping, making the algorithm a bit more efficient.

fun main() {

    val numbers = intArrayOf(29, 10, 14, 37, 13)

    println("Original Array: ${numbers.joinToString()}")

    for (i in numbers.indices) {

        var minIndex = i

        for (j in i + 1 until numbers.size) {

            if (numbers[j] < numbers[minIndex]) {
                minIndex = j
            }

        }

        if (minIndex != i) {

            val temp = numbers[i]
            numbers[i] = numbers[minIndex]
            numbers[minIndex] = temp

        }

    }

    println("Sorted Array: ${numbers.joinToString()}")

}

Here, the check if (minIndex != i) ensures that we only swap when necessary. This version behaves the same as the basic one but avoids doing extra work when the array is already partly sorted. It’s a good example for beginners to learn how to make small yet meaningful improvements in performance without changing the algorithm’s structure.

Program 3: Selection Sort Using Recursion

This program shows how to use recursion instead of loops. The same logic applies—find the smallest element and move it to its correct place—but the function calls itself to sort the rest of the array.

fun selectionSortRecursive(arr: IntArray, start: Int = 0) {

    if (start >= arr.size - 1) return

    var minIndex = start

    for (i in start + 1 until arr.size) {

        if (arr[i] < arr[minIndex]) {
            minIndex = i
        }

    }

    val temp = arr[start]
    arr[start] = arr[minIndex]
    arr[minIndex] = temp

    selectionSortRecursive(arr, start + 1)

}

fun main() {

    val numbers = intArrayOf(64, 25, 12, 22, 11)

    println("Original Array: ${numbers.joinToString()}")

    selectionSortRecursive(numbers)

    println("Sorted Array: ${numbers.joinToString()}")

}

In this recursive version, the function sorts one element at a time. It finds the smallest element in the unsorted part and swaps it into place, then calls itself to sort the remaining elements. Recursion helps beginners understand how a problem can be broken down into smaller versions of itself. Although recursion isn’t the most efficient way for Selection Sort, it’s a helpful exercise to strengthen your understanding of both recursion and sorting algorithms.

Program 4: Selection Sort in Descending Order

Sometimes, you may want to sort numbers from largest to smallest instead of the other way around. This version makes that easy by changing the comparison condition.

fun main() {

    val numbers = intArrayOf(15, 3, 9, 8, 5)

    println("Original Array: ${numbers.joinToString()}")

    for (i in numbers.indices) {

        var maxIndex = i

        for (j in i + 1 until numbers.size) {

            if (numbers[j] > numbers[maxIndex]) {
                maxIndex = j
            }

        }

        val temp = numbers[i]
        numbers[i] = numbers[maxIndex]
        numbers[maxIndex] = temp

    }

    println("Sorted in Descending Order: ${numbers.joinToString()}")

}

Here, the logic remains mostly the same as before, but the comparison numbers[j] > numbers[maxIndex] ensures that the biggest element is moved to the front. This simple change helps you see how Selection Sort can be easily adapted to sort in either order. It’s also a fun way to experiment with conditions and observe how they affect program behavior.

Program 5: Selection Sort Using Kotlin Functions

This version shows how you can use Kotlin’s flexibility to write a slightly cleaner version of Selection Sort, using a custom function that can be reused anywhere in your code.

fun selectionSort(arr: IntArray): IntArray {

    for (i in arr.indices) {

        var minIndex = i

        for (j in i + 1 until arr.size) {

            if (arr[j] < arr[minIndex]) {
                minIndex = j
            }

        }

        val temp = arr[i]
        arr[i] = arr[minIndex]
        arr[minIndex] = temp

    }

    return arr

}

fun main() {

    val numbers = intArrayOf(20, 12, 10, 15, 2)

    println("Original Array: ${numbers.joinToString()}")

    val sortedArray = selectionSort(numbers)

    println("Sorted Array: ${sortedArray.joinToString()}")

}

This approach wraps the sorting logic inside a reusable function, making your code cleaner and easier to maintain. Beginners can use this to understand how to structure code better and build modular, reusable functions — a key part of writing professional Kotlin programs.

Frequently Asked Questions (FAQ)

Here are some common questions beginners often ask about Selection Sort in Kotlin.

Q1: What is Selection Sort in Kotlin?
Selection Sort is a simple sorting algorithm that repeatedly selects the smallest (or largest) element from the unsorted section and moves it to its correct position in the array.

Q2: Is Selection Sort efficient?
Not really for large datasets. Selection Sort has a time complexity of O(n²), making it slower than more advanced algorithms like Quick Sort or Merge Sort. However, it’s excellent for learning the basics of sorting.

Q3: Can Selection Sort be used to sort strings in Kotlin?
Yes, it can. You just need to use an array of strings and modify the comparison condition accordingly.

Q4: What’s the main difference between Bubble Sort and Selection Sort?
Bubble Sort swaps elements multiple times per pass, while Selection Sort finds the minimum element first and swaps only once per pass. This usually means fewer swaps in Selection Sort.

Q5: Does Selection Sort work for both ascending and descending order?
Yes, by simply changing the comparison operator (< or >) inside the loop, you can make it sort in either ascending or descending order.

Conclusion

Selection Sort may not be the fastest sorting algorithm, but it’s one of the best for beginners to start with. It clearly shows how to find the smallest or largest element, how to perform swaps, and how sorting gradually brings order to a list. By experimenting with different versions—using loops, recursion, and even function-based approaches—you’ll gain a strong understanding of how algorithms work in Kotlin.

The beauty of Selection Sort lies in its simplicity. Once you fully grasp it, you’ll find it much easier to learn more advanced sorting techniques later on. So, open your Kotlin editor, try out these programs, and watch how your code neatly arranges numbers into order. Practice a little every day, and you’ll soon feel confident with sorting algorithms and Kotlin programming alike.

Scroll to Top