Bubble Sort Algorithm in Scala

1. Introduction

Bubble Sort is a simple sorting algorithm that works by repeatedly stepping through the list, comparing each pair of adjacent items, and swapping them if they are in the wrong order. The procedure is repeated for every item in the list. Despite its simplicity, it is not the most efficient algorithm for large lists.

2. Implementation Steps

1. Start with the first element in the list.

2. Compare the current element with the next element.

3. If the current element is greater than the next element, swap them.

4. Move to the next element and repeat steps 2-3 until the end of the list.

5. Go back to the beginning and repeat the entire process until no swaps are needed.

3. Implementation in Scala

object BubbleSort {
  def sort(arr: Array[Int]): Array[Int] = {
    for (i <- arr.indices) {
      for (j <- 0 until arr.length - i - 1) {
        // Swap if the element found is greater than the next element
        if (arr(j) > arr(j + 1)) {
          val temp = arr(j)
          arr(j) = arr(j + 1)
          arr(j + 1) = temp
        }
      }
    }
    arr
  }
}

Client Code:

val arr = Array(64, 34, 25, 12, 22, 11, 90)
println("Original Array: " + arr.mkString(", "))
val sortedArr = BubbleSort.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 BubbleSort: This is the singleton object for the Bubble Sort algorithm in Scala.

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

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

4. for (j <- 0 until arr.length - i - 1): Nested loop to go through the array multiple times, reducing its size with every iteration to avoid rechecking already sorted elements.

5. if (arr(j) > arr(j + 1)): This checks if the current element is greater than the next element.

6. Inside the if condition: This swaps the elements if the current element is greater than the next one.

7. Client Code: This demonstrates how to use the BubbleSort object to sort an array.

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


Comments