Bubble Sort is also a simple and intuitive sorting algorithm. It repeatedly goes through the sequence to be sorted, comparing two elements at a time and swapping them if they are in the wrong order. The task of visiting a sequence is repeated until there are no more elements to swap, that is, the sequence has been sorted. The algorithm gets its name from the fact that smaller elements slowly “float” to the top of the list through swaps.

Algorithm steps

  1. Compare adjacent elements. If the first one is bigger than the second, swap them both.
  2. Do the same for each pair of adjacent elements, from the first pair at the beginning to the last pair at the end. When we do that, the last element is going to be the largest number.
  3. Repeat this step for all elements except the last one.
  4. Keep repeating the above steps for fewer and fewer elements at a time until there are no more pairs to compare.

Dynamic graph demonstration

JavaScript code implementation

const bubbleSort = (arr) = > {
    const len = arr.length
    for (let i = 0; i < len - 1; i++) {
        for (let j = 0; j < len - 1 - i; j++) {
            if (arr[j] > arr[j + 1]) {
                [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]
            }
        }
    }
    return arr
}
Copy the code

Python code implementation

def bubbleSort(arr) :
    for i in range(1.len(arr)):
        for j in range(0.len(arr) - i):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
    return arr
Copy the code