Bubble sort compares adjacent elements and swaps them if they are in the wrong order. The implementation uses two nested for loop to check two numbers in an array. The optimized solution uses a flag to skip the remaining passes.

Bubble sort


How bubble sort works?

Bubble sort compares adjacent elements and swaps them if they are in the wrong order. The algorithm is named for the way smaller or larger elements “bubble” to the top of the list.

What is bubble sort complexity?

Time complexity is O(n 2) average and worst. The optimized solution has O(n) best time. Bubble sort is for beginners to explore the sorting techniques. The space complexity is O(1), it is an in-place operation.

How to implement bubble sort in Java?

The implementation uses two nested for loop to compare two adjacent numbers in an array. If they are not ordered, swap their positions.

bubble sort doodle


Implement bubble sort

Java

Javascript

Python

Doodle

bubble sort doodle


Free download

Download Java, JavaScript and Python code
Insertion sort
Sorting doodles compilation (YouTube)