Scala Program to Implement Insertion Sort

Scala Program to Implement Insertion Sort

Insertion Sort is one of the most traditional and easy-to-understand sorting algorithms ever created. It works in a simple and familiar way, much like how someone might sort cards in their hands. You take one value at a time and place it where it belongs among the already sorted values. This slow and careful approach makes it perfect for beginners, because everything happens step by step, and there are no confusing jumps or surprises.

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

Even though Insertion Sort is not the fastest method for large lists, it shines in smaller tasks and in situations where data is almost sorted. Many classic systems used it because of its clean and predictable behavior. Today, it is still taught widely because it builds strong foundations for understanding how sorting works in Scala and in many other programming languages. Once you understand the heart of Insertion Sort, you will find it much easier to explore more advanced sorting algorithms later on.

Program 1: Basic Insertion Sort Using Loops

This first program shows the classic loop-based version of Insertion Sort. It starts from the second element, moves backwards, and places each value exactly where it should be. This makes it easy for beginners to see how the sorted part of the array slowly grows.

object InsertionSortBasic {

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

    val data = Array(9, 3, 5, 1, 7)

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

      val key = data(i)
      var j = i - 1

      while (j >= 0 && data(j) > key) {
        data(j + 1) = data(j)
        j -= 1
      }

      data(j + 1) = key

    }

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

  }

}

The program works by treating the left side of the array as the sorted section. Each new element is picked up and gently shifted into the correct position, creating order one step at a time. Beginners usually enjoy this version because the shifting process is straightforward and easy to imagine.

Program 2: Insertion Sort Wrapped in a Reusable Method

This version places the sorting logic in a separate method and keeps the main function clean. It helps beginners understand how organizing code into smaller blocks improves readability and follows traditional coding habits.

object InsertionSortMethod {

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

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

      val key = data(i)
      var j = i - 1

      while (j >= 0 && data(j) > key) {
        data(j + 1) = data(j)
        j -= 1
      }

      data(j + 1) = key

    }

    data

  }

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

    val data = Array(12, 4, 6, 2, 10)
    val sorted = insertionSort(data)

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

  }

}

This method-based structure helps beginners learn how to build reusable functions. It shows how logic can be grouped together neatly, making it easier to test, maintain, and understand. It also gives a more traditional feel to the program, which is often helpful for clarity.

Program 3: Insertion Sort Using Recursion

This program uses recursion instead of loops, showing beginners a different way to think about solving the same problem. It breaks the work into smaller steps, where each call handles a slightly smaller piece of the list.

object InsertionSortRecursion {

  def sortRec(data: Array[Int], n: Int): Unit = {

    if (n <= 1) return

    sortRec(data, n - 1)

    val key = data(n - 1)
    var j = n - 2

    while (j >= 0 && data(j) > key) {
      data(j + 1) = data(j)
      j -= 1
    }

    data(j + 1) = key

  }

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

    val data = Array(14, 9, 3, 7, 2)

    sortRec(data, data.length)

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

  }

}

The recursive version behaves the same as the loop-based one, but it organizes the process in a way that feels more mathematical. It helps beginners understand how a problem can be reduced step by step, with each recursive call handling a smaller chunk of the list.

Program 4: Insertion Sort Using a Functional Style with Immutable Lists

Scala allows functional programming, so this version shows how to write Insertion Sort using immutable lists. Instead of changing the original list, it builds a new sorted list piece by piece.

object InsertionSortFunctional {

  def insert(x: Int, sorted: List[Int]): List[Int] = {

    sorted match {

      case Nil => List(x)
      case head :: tail =>
        if (x < head) x :: sorted
        else head :: insert(x, tail)

    }

  }

  def insertionSort(list: List[Int]): List[Int] = {
    list.foldLeft(List[Int]())((sorted, x) => insert(x, sorted))
  }

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

    val data = List(5, 2, 8, 1, 6)
    val result = insertionSort(data)

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

  }

}

This version is useful for beginners exploring functional programming because it avoids altering data directly. Instead, it constructs a new list each time an element is inserted. This teaches a traditional functional habit of working with clean, unchanging values.

Program 5: Insertion Sort Using While Loops Only

This final version keeps things simple by using only while loops. It offers a neat, traditional structure that may feel familiar to those coming from older programming languages.

object InsertionSortWhile {

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

    val data = Array(16, 4, 9, 2, 11)
    var i = 1

    while (i < data.length) {

      val key = data(i)
      var j = i - 1

      while (j >= 0 && data(j) > key) {
        data(j + 1) = data(j)
        j -= 1
      }

      data(j + 1) = key
      i += 1

    }

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

  }

}

This version is helpful for beginners who prefer simple and predictable loops. By controlling the flow manually, it becomes easier to visualize each step and understand how values shift to make room for the key.

Frequently Asked Questions (FAQ)

This section answers the common questions many learners ask when exploring Insertion Sort in Scala. Each explanation is written gently and plainly so beginners can understand the ideas without feeling overwhelmed.

Q1: Why is Insertion Sort good for beginners?
Insertion Sort is good for beginners because it follows a simple, step-by-step pattern that is easy to picture. The way each value is picked and placed into the correct position makes the whole process clear, which helps new learners understand how sorting works at a basic level.

Q2: Is Insertion Sort faster than Selection Sort?
Insertion Sort can be faster than Selection Sort when the data is almost sorted. It needs fewer comparisons and shifts in these cases, allowing it to finish sooner. However, for fully unsorted data, both behave in a similar way.

Q3: Can Insertion Sort be used on strings in Scala?
Yes, Insertion Sort works with strings as long as Scala can compare them. The same idea of picking a value and placing it in the right spot applies to text the same way it applies to numbers. This makes the algorithm flexible and easy to use on many kinds of data.

Q4: What is the main idea behind Insertion Sort?
The main idea is to build the sorted part of the list one value at a time. Each new value is removed from the unsorted section and inserted into the correct position in the sorted section. This creates a neat and ordered list step by step.

Q5: When is Insertion Sort most efficient?
Insertion Sort is most efficient when the data is already sorted or almost sorted. In these cases, only a few shifts are needed, and the algorithm finishes quickly. It also works well for small datasets where its simple approach is more than enough.

Conclusion

Insertion Sort remains one of the cleanest and easiest sorting methods to learn, especially for beginners. It follows a simple and traditional pattern where each value finds its proper place, making the whole process clear and predictable. With the different Scala programs shown above, you now have several ways to understand and implement this algorithm, whether through loops, recursion, or functional programming.

As you continue practicing, try changing the data, modifying the code, or even comparing it with other sorting methods. Each experiment helps you grow as a programmer and strengthens your understanding of how sorting works in Scala. Keep exploring one step at a time, and your confidence will grow steadily.

Scroll to Top