Bubble Sort

FastSlow
Initializing...
Time Complexity
Best
O(n)O(n)
Average
O(n2)O(n^2)
Worst
O(n2)O(n^2)
Space Complexity
O(1)O(1)
StabilityTRUE
In-placeTRUE

Explanation

What is Bubble Sort?

Bubble Sort is a simple 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 the list is sorted. The algorithm is named for the way larger elements "bubble" up to the end of the list.

Algorithm Steps

  1. Compare two adjacent values from the beginning of the array.
  2. If the left value is higher than the right, swap them.
  3. Repeat this until the end of the array. After the first pass, the largest element is placed at the right end.
  4. Repeat the above for the unsorted part of the array.

Time Complexity

  • Worstcase: O(n2)O(n^2)
  • Average: O(n2)O(n^2)
  • Bestcase: O(n)O(n) (when already sorted)

Pseudo Code

1procedure bubbleSort(list)
2 for i from 0 to list.length - 1
3 for j from 0 to list.length - i - 1
4 if list[j] > list[j + 1]
5 swap(list[j], list[j + 1])
6end procedure
Sponsor Ad