Course lesson

Sort an Array with a JavaScript do while Loop using Bubble Sort

Bubble sort is often one of the first sorting algorithms people learn because it closely resembles how we might physically sort a collection of items. We loop through our list of items, comparing our current item with the next one. If our current item is less...

Duration
3 min
Access
Pro
Transcript
Available

Bubble sort is often one of the first sorting algorithms people learn because it closely resembles how we might physically sort a collection of items. We loop through our list of items, comparing our current item with the next one. If our current item is less than the next one, we swap them. We continue looping through the list until we make a loop without any swaps.

This is a very inefficient algorithm with a time complexity of O(n^2). Given a list of length n, we must compare each item against every other item in the list, which gives us n * n, or rather n^2. That means for a list of length 10, our worst case scenario will require 100 loops to sort our list. A list just twice as long will take 4x as many loops to solve.