Scala program to implement bubble sort

1. Introduction

Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted. In this blog post, we'll dive into a Scala program that implements the bubble sort algorithm.

2. Program Steps

1. Set up the Scala environment.

2. Create an object to house the main function.

3. Define an array of integers.

4. Implement the bubbleSort function to sort the array using the Bubble Sort algorithm.

5. Call the bubbleSort function within the main function.

6. Print the sorted array.

7. Run the program.

3. Code Program

object BubbleSortApp {
  def main(args: Array[String]): Unit = {
    val arr = Array(64, 34, 25, 12, 22, 11, 90)  // array to be sorted
    println("Original Array:")
    arr.foreach(println)

    bubbleSort(arr)  // Sort the array

    println("\nSorted Array:")
    arr.foreach(println)
  }

  // Function to implement bubble sort
  def bubbleSort(arr: Array[Int]): Unit = {
    val n = arr.length
    for(i <- 0 until n-1; j <- 0 until n-i-1) {
      if (arr(j) > arr(j+1)) {
        // swap arr(j) and arr(j+1)
        val temp = arr(j)
        arr(j) = arr(j+1)
        arr(j+1) = temp
      }
    }
  }
}

Output:

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

Explanation:

1. We start by defining an object BubbleSortApp. In Scala, the main method, the entry point of the program, resides inside an object.

2. Inside the main function, an array arr is defined that we intend to sort.

3. We print the original, unsorted array for comparison.

4. The function bubbleSort is the core of the program. It accepts an array and sorts it using the Bubble Sort algorithm. This function uses two nested loops to repeatedly compare and swap elements if they are in the wrong order.

5. Inside the bubbleSort function, elements are compared, and if an element is greater than its next element, they are swapped.

6. The outer loop in bubbleSort ensures that the algorithm runs for n-1 passes, where n is the number of elements in the array.

7. After calling bubbleSort, the program prints the sorted array, showcasing the result of the sorting operation.


Comments