ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Scala Bubble Sort Implementation

Scala

Goal -- WPM

Ready
Exercise Algorithm Area
1object BubbleSort {
2
3/**
4* Sorts an array of integers in ascending order using the Bubble Sort algorithm.
5* Bubble Sort repeatedly steps through the list, compares adjacent elements,
6* and swaps them if they are in the wrong order. The pass through the list is
7* repeated until the list is sorted.
8*
9* @param arr The array of integers to be sorted.
10*/
11def bubbleSort(arr: Array[Int]): Unit = {
12val n = arr.length
13var swapped: Boolean = false
14
15// Outer loop for passes. It runs at most n-1 times.
16for (i <- 0 until n - 1) {
17swapped = false // Reset swap flag for each pass
18
19// Inner loop for comparisons and swaps.
20// The last i elements are already in place, so we don't need to check them.
21for (j <- 0 until n - 1 - i) {
22// Compare adjacent elements
23if (arr(j) > arr(j + 1)) {
24// Swap elements if they are in the wrong order
25val temp = arr(j)
26arr(j) = arr(j + 1)
27arr(j + 1) = temp
28swapped = true // Mark that a swap occurred
29}
30}
31
32// If no two elements were swapped by inner loop, then break
33// This is an optimization: if an array is already sorted,
34// we don't need to continue passes.
35if (!swapped) {
36return
37}
38}
39}
40
41/**
42* Main method to demonstrate the Bubble Sort algorithm.
43* It sorts several arrays, including an already sorted array,
44* a reverse-sorted array, and an array with duplicate elements,
45* to showcase the algorithm's behavior and optimization.
46*/
47def main(args: Array[String]): Unit = {
48// Test case 1: General unsorted array
49val arr1 = Array(64, 34, 25, 12, 22, 11, 90)
50println(s"Original array 1: ${arr1.mkString(", ")}")
51bubbleSort(arr1)
52println(s"Sorted array 1: ${arr1.mkString(", ")}") // Expected: 11, 12, 22, 25, 34, 64, 90
53println("---------------------")
54
55// Test case 2: Already sorted array (to test optimization)
56val arr2 = Array(1, 2, 3, 4, 5)
57println(s"Original array 2: ${arr2.mkString(", ")}")
58bubbleSort(arr2)
59println(s"Sorted array 2: ${arr2.mkString(", ")}") // Expected: 1, 2, 3, 4, 5
60println("---------------------")
61
62// Test case 3: Reverse sorted array
63val arr3 = Array(5, 4, 3, 2, 1)
64println(s"Original array 3: ${arr3.mkString(", ")}")
65bubbleSort(arr3)
66println(s"Sorted array 3: ${arr3.mkString(", ")}") // Expected: 1, 2, 3, 4, 5
67println("---------------------")
68
69// Test case 4: Array with duplicate elements
70val arr4 = Array(5, 1, 4, 2, 8, 4, 5)
71println(s"Original array 4: ${arr4.mkString(", ")}")
72bubbleSort(arr4)
73println(s"Sorted array 4: ${arr4.mkString(", ")}") // Expected: 1, 2, 4, 4, 5, 5, 8
74println("---------------------")
75
76// Test case 5: Empty array
77val arr5 = Array[Int]()
78println(s"Original array 5: ${arr5.mkString(", ")}")
79bubbleSort(arr5)
80println(s"Sorted array 5: ${arr5.mkString(", ")}") // Expected: (empty)
81println("---------------------")
82}
83}
Algorithm description viewbox

Scala Bubble Sort Implementation

Algorithm description:

This Scala program implements the Bubble Sort algorithm to sort an array of integers in ascending order. The algorithm works by repeatedly stepping through the list, comparing adjacent elements, and swapping them if they are in the wrong order. This process is repeated until the list is sorted. An optimization is included to stop early if a pass completes without any swaps, indicating the array is already sorted.

Algorithm explanation:

The `bubbleSort` function takes an `Array[Int]` and sorts it in place. It uses two nested loops. The outer loop controls the number of passes, running up to `n-1` times, where `n` is the array length. The inner loop iterates through the unsorted portion of the array, comparing adjacent elements (`arr(j)` and `arr(j+1)`). If `arr(j)` is greater than `arr(j+1)`, they are swapped. A `swapped` flag is used to track if any swaps occurred during a pass. If a pass completes with no swaps (`!swapped`), the array is sorted, and the function returns early. The time complexity of Bubble Sort is O(n^2) in the worst and average cases, and O(n) in the best case (already sorted array) due to the optimization. The space complexity is O(1) because it sorts in place and uses only a few extra variables.

Pseudocode:

function bubble_sort(array):
  n = length(array)
  for i from 0 to n-2:
    swapped = false
    for j from 0 to n-2-i:
      if array[j] > array[j+1]:
        swap(array[j], array[j+1])
        swapped = true
    if not swapped:
      break