← All Exercises

Bubble Sort Implementation

intermediatejavascript~20min

Background

Bubble sort is a simple comparison-based sorting algorithm often used for teaching sorting fundamentals and algorithm analysis.

Problem

Write a function that sorts an array of numbers in ascending order using the bubble sort algorithm with an optimization to exit early if no swaps occur.

Input

An array of numbers to be sorted.

Output

A new array sorted in ascending order.

Sample tests

Sample 1

Input: [5, 3, 8, 1, 2]
Expected: [1, 2, 3, 5, 8]

Your solution

Learning objective

Understand comparison-based sorting, swap mechanics, and algorithm optimization with early termination.