Bubble Sort Visualization

What is Bubble Sort Algorithm?

Bubble Sort is a simple and inefficient sorting algorithm that repeatedly compares adjacent elements in a list and swaps them if they are in the wrong order. It continues this process until the entire list is sorted. During each pass through the list, the largest (or smallest) element gradually "bubbles" up to its correct position. Bubble Sort is easy to understand and implement but tends to perform poorly on large or already sorted lists.

Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the input list element by element, comparing the current element with the one after it, swapping their values if needed. These passes through the list are repeated until no swaps had to be performed during a pass, meaning that the list has become fully sorted. The algorithm, which is a comparison sort, is named for the way the larger elements "bubble" up to the top of the list.

This simple algorithm performs poorly in real world use and is used primarily as an educational tool. More efficient algorithms such as quicksort, timsort, or merge sort are used by the sorting libraries built into popular programming languages such as Python and Java. However, if parallel processing is allowed, bubble sort sorts in O(n) time, making it considerably faster than parallel implementations of insertion sort or selection sort which do not parallelize as effectively.

JavaScript implementation

  function bubbleSort(arr) {
    const length = arr.length;

    for (let i = 0; i < length - 1; i++) {
      for (let j = 0; j < length - i - 1; j++) {
        if (arr[j] > arr[j + 1]) {
          // Swap the elements
          [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];

    return arr;

Go implementation

  func bubbleSort(arr []int) []int {
    n := len(arr)
    for i := 0; i < n-1; i++ {
      for j := 0; j < n-i-1; j++ {
        if arr[j] > arr[j+1] {
          arr[j], arr[j+1] = arr[j+1], arr[j]
    return arr

Python implementation

  def bubble_sort(arr):
      n = len(arr)
      for i in range(n - 1):
          for j in range(n - i - 1):
              if arr[j] > arr[j + 1]:
                  arr[j], arr[j + 1] = arr[j + 1], arr[j]

Source: Wikipedia