Scala Program to Implement Selection Sort

Scala Program to Implement Selection Sort

Selection Sort is one of the most traditional sorting algorithms, often taught early because it is easy to understand and follow. The idea behind it is very clear: you search through the list, find the smallest value, and place it at the front. Then you repeat the process with the rest of the list until everything is in the right order. Even though it may not be the fastest method, its structure helps beginners get comfortable with comparing values and thinking through small steps.

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 matters because it trains your mind to look for patterns and understand how sorting works behind the scenes. Many modern algorithms are built on ideas that also involve searching, comparing, and placing values in the right positions. Selection Sort gives you a gentle start before moving on to more complex techniques. While it is mostly used in small tasks today, it still carries a strong educational value, helping new programmers understand how data is arranged and why choosing the right algorithm can make a big difference.

Program 1: Basic Selection Sort Using Loops

This first program shows the classic version of Selection Sort written in Scala. It moves through the array, finds the smallest value in each pass, and swaps it into its proper position. This gives beginners a very clear view of how the algorithm behaves step by step.

object SelectionSortBasic {

  def main(args: Array[String]): Unit = {

    val data = Array(9, 4, 2, 7, 1)

    for (i <- data.indices) {

      var minIndex = i

      for (j <- i + 1 until data.length) {

        if (data(j) < data(minIndex)) {
          minIndex = j
        }

      }

      val temp = data(i)
      data(i) = data(minIndex)
      data(minIndex) = temp

    }

    println("Sorted Array: " + data.mkString(", "))

  }

}

This program works by treating each position from the start as the place where the next smallest number should sit. It searches the rest of the list to find that smallest number and then performs a simple swap. Beginners find this version easy because everything is laid out clearly with loops and simple comparisons.

Program 2: Selection Sort with a Helper Method

This second program separates the sorting logic into its own method. This keeps the main function cleaner and helps beginners learn how to write reusable code. It also gives a traditional structure where each part of the program does one job.

object SelectionSortMethod {

  def selectionSort(data: Array[Int]): Array[Int] = {

    for (i <- data.indices) {

      var minIndex = i

      for (j <- i + 1 until data.length) {

        if (data(j) < data(minIndex)) {
          minIndex = j
        }

      }

      val temp = data(i)
      data(i) = data(minIndex)
      data(minIndex) = temp

    }

    data

  }

  def main(args: Array[String]): Unit = {

    val data = Array(8, 3, 5, 2, 9)
    val result = selectionSort(data)

    println("Sorted Array: " + result.mkString(", "))

  }

}

This version is helpful because it shows how to break a problem into smaller parts. Beginners can focus on understanding the sorting logic inside the method and treat the main function as a clean place to test results. It also reflects traditional programming habits where code is kept neat and organized.

Program 3: Selection Sort Using Recursion

This program shows how Selection Sort can be written using recursion instead of loops. While recursion feels different at first, it gives beginners a new way of thinking—solving big problems by breaking them into smaller ones.

object SelectionSortRecursion {

  def selectionSort(data: Array[Int], start: Int): Unit = {

    if (start >= data.length - 1) return

    var minIndex = start

    for (i <- start + 1 until data.length) {

      if (data(i) < data(minIndex)) {
        minIndex = i
      }

    }

    val temp = data(start)
    data(start) = data(minIndex)
    data(minIndex) = temp

    selectionSort(data, start + 1)

  }

  def main(args: Array[String]): Unit = {

    val data = Array(11, 6, 3, 10, 4)

    selectionSort(data, 0)

    println("Sorted Array: " + data.mkString(", "))

  }

}

The recursive version works exactly like the loop-based one, but instead of repeating the steps with loops, the function calls itself with the next starting index. This teaches beginners how recursion moves through a problem naturally, reducing the work piece by piece.

Program 4: Selection Sort Using Immutable Lists (Functional Style)

Scala also supports functional programming, so this program shows a version of Selection Sort that works with immutable lists. Instead of swapping elements directly, it builds and returns a new list each time.

object SelectionSortFunctional {

  def findMin(list: List[Int]): Int = list.min

  def removeFirst(list: List[Int], value: Int): List[Int] = {

    val index = list.indexOf(value)
    list.patch(index, Nil, 1)

  }

  def selectionSort(list: List[Int]): List[Int] = {

    if (list.isEmpty) list
    else {

      val minValue = findMin(list)
      minValue :: selectionSort(removeFirst(list, minValue))

    }

  }

  def main(args: Array[String]): Unit = {

    val data = List(7, 2, 9, 1, 6)
    val result = selectionSort(data)

    println("Sorted List: " + result.mkString(", "))

  }

}

This program is useful for beginners who want to explore the functional side of Scala. Instead of modifying a list in place, it creates new versions of the list as it removes the smallest element and builds the sorted result. It teaches a different way of thinking—working with values instead of changing them.

Program 5: Selection Sort with a Custom Function for Minimum Index

Here, the program uses a custom helper function that finds the index of the smallest value from a given starting point. This makes the sorting steps more readable and shows beginners how to split a task into smaller traditional units.

object SelectionSortCustomMin {

  def minIndex(data: Array[Int], start: Int): Int = {

    var minIndex = start

    for (i <- start + 1 until data.length) {
      if (data(i) < data(minIndex)) minIndex = i
    }

    minIndex

  }

  def main(args: Array[String]): Unit = {

    val data = Array(15, 4, 9, 1, 3)

    for (i <- data.indices) {

      val minIdx = minIndex(data, i)
      val temp = data(i)
      data(i) = data(minIdx)
      data(minIdx) = temp

    }

    println("Sorted Array: " + data.mkString(", "))

  }

}

This version gives beginners an easy-to-read structure by separating the “find minimum” part from the main sorting loop. It helps them appreciate how breaking work into functions keeps programs clean and structured.

Frequently Asked Questions (FAQ)

This section helps clear common questions that many beginners ask when learning Selection Sort in Scala. Each answer is explained in a calm and easy way so new learners can understand the idea without struggling.

Q1: Why is Selection Sort useful for beginners?
Selection Sort is useful because it teaches the basic idea of searching and placing values in the correct spot. It does not have confusing steps, which makes it easier for beginners to follow. Once this simple pattern becomes familiar, learning more advanced sorting methods becomes much easier.

Q2: Is Selection Sort faster than Bubble Sort?
Selection Sort is usually a little faster than Bubble Sort because it makes fewer swaps. Even though both take similar time overall, Selection Sort tends to behave more steadily and cleanly. This makes it feel a bit smoother for small sets of data.

Q3: Can Selection Sort be used on strings in Scala?
Yes, Selection Sort can sort strings just as it sorts numbers. As long as Scala can compare two values, the same steps of finding the smallest one and placing it first will work. This makes the algorithm flexible and easy to apply to many kinds of data.

Q4: What is the main idea behind Selection Sort?
The main idea is simple: find the smallest value in the unsorted part of the list and put it where it belongs. After that, move to the next position and repeat the same process. This step-by-step action continues until the whole list is sorted from start to finish.

Q5: Is Selection Sort good for large datasets?
Selection Sort is not a good choice for very large datasets because it takes a long time to finish. It works best for small tasks where speed is not a big concern. For bigger collections, more advanced algorithms are normally used instead.

Conclusion

Selection Sort may not be the fastest sorting algorithm, but it remains one of the clearest and most traditional ways to learn how sorting works. Its step-by-step nature helps beginners understand comparisons, searching, and swapping without feeling overwhelmed. With the different Scala programs shown above, you now have several ways to write Selection Sort, from loops to recursion and functional style.

As you keep practicing, you will notice how simple ideas grow into stronger problem-solving skills. Feel free to experiment with different data, change parts of the code, and explore other algorithms. Each small step builds your confidence and opens the door to more advanced programming techniques in Scala.

Scroll to Top