Skip to main content
Back to ChallengesImplement Bubble SortEasy 15 min

Implement Bubble Sort

Write a function that takes in an array of integers and returns a sorted version of that array using the Bubble Sort algorithm.

Bubble Sort works by repeatedly stepping through the list, comparing adjacent elements and swapping them if they are in the wrong order. The pass through the list is repeated until the list is sorted.

Examples

Input: arr = [8, 5, 2, 9, 5, 6, 3]
Output: [2, 3, 5, 5, 6, 8, 9]
The array is sorted in ascending order.

Constraints

  • 1 <= arr.length <= 1000
  • -10^4 <= arr[i] <= 10^4

Complexity Analysis

Time
O(N^2)
double loop over the array in the worst/average case.
Space
O(1)
sorts in place.

Test Cases

#1 Standard unsorted array
Input: arr = [8,5,2,9,5,6,3]
Expected: [2,3,5,5,6,8,9]
#2 Already sorted array
Input: arr = [1,2,3]
Expected: [1,2,3]
JavaScript
Output
Click "Run Code" to see output here...