bubbleSort

Hard · Array Manipulations · 1 test cases

Implement the bubble sort algorithm to sort an array of numbers in ascending order.

Examples

bubbleSort([1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]) → [1, 1, 2, 2, 4, 8, 32, 43, 43, 55, 63, 92, 123, 123, 234, 345, 5643]

Starter code

function bubbleSort(arr) {

}

Complexity of the optimal solution

Time O(n²), space O(1). Bubble sort uses two nested loops to iterate through the array. The outer loop runs n times and the inner loop runs about n times for each outer iteration, resulting in a quadratic time complexity. The sorting is done in-place, so it has constant space complexity.

Solve bubbleSort in the browser