Login

Bubble Sort

Implement a function that sorts an array using the bubble sort algorithm.

Advanced


Instructions

Bubble Sort is a 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 no swaps are needed, which indicates that the list is sorted.

Implement a function bubbleSort that takes an array of integers as input and returns the sorted array using the Bubble Sort algorithm.

The function should have the following signature:

const bubbleSort = (myArray) => {...}

The function should return an array of integers in non-decreasing order.

For example, bubbleSort([9,4,2,1,5]) should return [1,2,4,5,9].

Tip

The Bubble Sort algorithm works as follows:

  1. Start with the first element in the array.
  2. Compare it with the next element.
  3. If the first element is greater than the next element, swap them.
  4. Move to the next element and repeat steps 2 and 3.
  5. Continue this process until no swaps are needed.

PS: The checks doesn't check if you sorted the array correctly using bubble sort, just if the array is sorted. Make you best.

Tests
0/4
Function Call:
Expected:
bubbleSort([9,4,2,1,5])
[ 1, 2, 4, 5, 9 ]
Run test

bubbleSort([])
[]
Run test

Hidden Test
?
Run test

Hidden Test
?
Run test

See Solution

Solution

const bubbleSort = (arr) => {
    const n = arr.length;
    for (let i = 0; i < n - 1; i++) {
        for (let j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                // Swap arr[j] and arr[j+1]
                [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
            }
        }
    }
    return arr;

}

Algorithm Detailed Explanation

  1. The outer loop runs from 0 to n-1, where n is the number of elements in the array.
  2. The inner loop runs from 0 to n-i-1, where i is the current iteration of the outer loop.
  3. In each iteration of the inner loop, we compare adjacent elements and swap them if they are in the wrong order.
  4. After each iteration of the outer loop, the largest element in the unsorted part of the array bubbles up to its correct position.
  5. The algorithm repeats this process until no swaps are needed, indicating that the array is sorted.

Complexity Analysis

  • Time complexity: O(n^2) in the worst case, where n is the number of elements in the array.
  • Space complexity: O(1) as the algorithm sorts the array in place without using any extra space.
Any improvement idea? Share with us!