Selection Sort Algorithm in Scala

1. Introduction

Selection Sort is a simple comparison-based sorting algorithm. The primary idea behind the selection sort is dividing the list into two parts: the sorted part at the left end and the unsorted part at the right end. Initially, the sorted part is empty, while the unsorted part contains all the elements. With each iteration, the smallest (or largest, depending on the sorting order) element from the unsorted sublist is picked and moved to the sorted sublist.

2. Implementation Steps

1. Start with the first position as the minimum.

2. Compare the minimum with the next element in the list until the end.

3. If any element is smaller than the current minimum, update the minimum.

4. Swap the minimum element with the first element.

5. Move the boundary of the unsorted sublist to the next element and repeat the process.

3. Implementation in Scala

object SelectionSort {
  def sort(arr: Array[Int]): Array[Int] = {
    for (i <- arr.indices) {
      // Assume the minimum is the first element
      var minIdx = i
      // Loop through the list to find the minimum element
      for (j <- i + 1 until arr.length) {
        if (arr(j) < arr(minIdx)) {
          minIdx = j
        }
      }
      // Swap the minimum element with the first element
      val temp = arr(minIdx)
      arr(minIdx) = arr(i)
      arr(i) = temp
    }
    arr
  }
}

Client Code:

val arr = Array(64, 34, 25, 12, 22, 11, 90)
println("Original Array: " + arr.mkString(", "))
val sortedArr = SelectionSort.sort(arr)
println("Sorted Array: " + sortedArr.mkString(", "))

Output:

Original Array: 64, 34, 25, 12, 22, 11, 90
Sorted Array: 11, 12, 22, 25, 34, 64, 90

Explanation:

1. object SelectionSort: This is the singleton object for the Selection Sort algorithm in Scala.

2. sort(arr: Array[Int]): This is the method that performs the selection sort on an array of integers.

3. for (i <- arr.indices): We loop through the entire array.

4. var minIdx = i: We start by assuming that the minimum value is at the current index.

5. for (j <- i + 1 until arr.length): Nested loop to find the minimum value in the unsorted sublist.

6. if (arr(j) < arr(minIdx)): This checks if the current element is smaller than the previously identified minimum.

7. Inside the if condition: This updates the index of the new minimum value.

8. After the nested loop: We swap the identified minimum value with the value at the current index of the outer loop.

9. Client Code: This demonstrates how to use the SelectionSort object to sort an array.

With this approach, we successfully sort the array in ascending order using the Selection Sort algorithm in Scala.


Comments