How bubble sort works:

Bubble sort works by swapping adjacent elements if the 2 elements are not sorted. An example of this is shown below. The element at index 0, is bigger than element at index 1, therefore, they we swap them. In the following iterations number 4 bubbles up until it reaches the second element with value 4. Then in all consecutive iterations all the elements are sorted.

const swap = (array, firstPosition, secondPosition) => {
  const temp = array[firstPosition];
  array[firstPosition] = array[secondPosition];
  array[secondPosition] = temp;
  return array;
};

const bubbleSort = (unsortedArray) => {
  const arr = [...unsortedArray];

  const arraySize = unsortedArray.length;
  for (let i = 0; i < arraySize - 1; i++) {
    for (let j = 0; j < arraySize - i - 1; j++) {
      if (arr[j] > arr[j + 1]) {
        swap(arr, j, j + 1);
      }
    }
  }
  return arr;
};

const unsortedArr = [4, 3, 1, 2, 3, 4, 5];

const result = bubbleSort(unsortedArr);
console.log(...result);

When swap is happening:

  1. [3, 4, 1, 2, 3, 4, 5]
  2. [3, 1, 4, 2, 3, 4, 5]
  3. [3, 1, 2, 4, 3, 4, 5]
  4. [3, 1, 2, 3, 4, 4, 5]
  5. [1, 3, 2, 3, 4, 4, 5]

Last, we have the array with all the elements sorted. The complexity of the algorithm is O(n^2).

Result: [1, 2, 3, 3, 4, 4, 5]