Bubble sort is an algorithm that compares the adjacent elements and swaps their positions if they are not in the intended order. The order can be ascending or descending.
bubbleSort(array)
swapped <- false
for i <- 1 to indexOfLastUnsortedElement-1
if leftElement > rightElement
swap leftElement and rightElement
swapped <- true
end bubbleSort
Bubble Sort is one of the simplest sorting algorithms. Two loops are implemented in the algorithm.
- If we want to sort in ascending order and the array is in descending order then, the worst case occurs.
- If the array is already sorted, then there is no need for sorting.
- It occurs when the elements of the array are in jumbled order (neither ascending nor descending).
Space Complexity is O(2) because the variable swapped adds to the space complexity.
It is used in the following cases where
- the complexity of the code does not matter.
- a short code is preffered.
- Cpp
g++ bubbleSort.cpp<br> ./a.out
- Python
python3 bubbleSort\.py
- C
gcc bubbleSort.c ./a.out
- Java
javac bubbleSort.java java bubbleSort
- JavaScript
node bubbleSort.js