18
OctBubble Sort Algorithm
Bubble Sort Algorithm
The Bubble Sort Algorithm 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 process continues until no more swaps are needed, indicating the list is sorted. It is named "bubble sort" because smaller elements "bubble" to the top of the list with each iteration.
85% of top tech companies prioritize DSA expertise in hiring. Start your journey with our Free Data Structures and Algorithms Course now!
Example:
- Input: nums = [64, 34, 25, 12, 22, 11, 90]
- Output: [11, 12, 22, 25, 34, 64, 90]
- Explanation: The array is sorted in ascending order.
Logic
Enter an array of numbers (comma-separated) to sort it using the Bubble Sort algorithm.
Program (Python - Bubble Sort Implementation)
The following Python code implements the Bubble Sort algorithm with O(n²) time complexity in the worst and average cases, where n is the length of the array.
def bubbleSort(nums):
n = len(nums)
for i in range(n):
# Flag to optimize by checking if any swaps occurred
swapped = False
# Last i elements are already in place
for j in range(0, n - i - 1):
if nums[j] > nums[j + 1]:
# Swap adjacent elements
nums[j], nums[j + 1] = nums[j + 1], nums[j]
swapped = True
# If no swaps occurred, array is sorted
if not swapped:
break
return nums
# Example usage
nums = [64, 34, 25, 12, 22, 11, 90]
print(bubbleSort(nums)) # Output: [11, 12, 22, 25, 34, 64, 90]
Output
For the input nums = [64, 34, 25, 12, 22, 11, 90], the output is:
[11, 12, 22, 25, 34, 64, 90]
Explanation:
The array is sorted in ascending order using the bubble sort algorithm.
India’s tech hubs have 12,000+ openings for certified Java full stack developers. Start now with our Java full stack training and seize prime opportunities!
Take our Datastructures skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.