Emma Bostian ✨

Posted on

# Bubble Sort In JavaScript

Bubble Sort is one of the most widely discussed algorithms, simply because of its lack of efficiency for sorting arrays. If an array is already sorted, Bubble Sort will only pass through the array once (using concept two below), however the worst case scenario is a run time of O(N²), which is extremely inefficient.

Even former President Barack Obama recognizes the inefficiency of Bubble Sort.

When we chart the growth-rate of O(N²), we see that, compared to other sorting algorithms like Merge Sort, which is O(N Log N), it grows at a much quicker scale.

Given the atrocity that is Bubble Sort, it’s still important to understand the algorithm and decipher why it’s so poor.

Let’s delve into two concepts for coding Bubble Sort.

# Concept 1

• Iterate through the array and check each element against the next element in the array.
• If the current element is larger than the next element, swap them.
• If it’s not greater, move the pointers up and compare the next two elements.
• Once we reach the end of the array, we know that the largest element is in the last position.
• Repeat this process N times where N is the length of the array, and each time, iterate up to the last-sorted element.

### Visualizing Concept 1

Let’s take a look at how this would be run on an array of length 6.

### Concept 1 Code

We need to have two pointers (two nested loops) for concept one. Each time we iterate through, the upper bound decreases by one, as we know that this index contains a sorted value.

``````function bubbleSortConcept1(arr) {
for (let j = arr.length - 1; j > 0; j--) {
for (let i = 0; i < j; i++) {
if (arr[i] > arr[i + 1]) {
let temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
}
}
}
``````

# Concept 2

• Iterate through the array and check each element against the next element in the array.
• If the current element is greater than the next item, swap them.
• Indicate that a swap has taken place.
• If a swap occurred, loop through the array again.
• We know that the array is sorted when no swaps have occurred.

### Concept 2 Code

We only need one pointer with this method, as we’re using a variable to store a Boolean, indicating whether or not a swap occurred. In contrast to concept one, this concept requires us to iterate through each item in the array each time we pass through it.

``````function bubbleSortConcept2(arr) {
let swapped;

do {
swapped = false;
console.log(arr);
arr.forEach((item, index) => {
if (item > arr[index + 1]) {
// Save the value to a variable so we don't lose it
let temp = item;
arr[index] = arr[index + 1];
arr[index + 1] = temp;
swapped = true;
}
})
} while (swapped);
}
``````

# Run Time

Bubble Sort is one of the most inefficient sorting algorithms coming in at O(N²). In the worst case scenario, we will have to compare each element against every other element in the array, hence O(N²).

Eugene Karataev

Two years ago on interview I was asked to write bubble sort on a paper. I guess it's the only sorting algorithm I can write without google help 😀

I'm a visual learner, so it's useful for me to visualize an algorihtm process. I created the bubble sort visualization to better grasp the concept.

You can fork and play with it here.

Hamza ERBAY

Thanks, Emma for the explanation.
Eugene, I m another visual learner too :) I want to put visualgo.net here. That's super helpful for understanding algorithms.

Eugene Karataev

Yeah, visualgo is a great resource to grasp algorithms by visualizing them step by step.

Emma Bostian ✨

Horrible interview!

Aslan French

I'm a designer who is learning to code and I found this a little confusing.

I don'tunderstand why you're nesting stuff the way you are in code. How can there be two ways of writing the code if the essential logical idea of the sort is the same?

Why do you callthem pointers? I thought pointers were a thing in c++ for telling a program where stuff was stored in memory?

Also I didn't understand what o(n^2) meant. I'm guessing that as the array length grows, the number of operations required grows exponentially? But why?

Hello! You are confused because you never studied Algorithm Analysis or Complexity Analysis. It is basically the study of algorithm performance... this course is the core of a Computer Scientist degree, for example!

1) How can there be two ways of writing the code if the essential logical idea of the sort is the same? => When analysing algorithms, you will discover it is common to do the same thing in a lot of different manners. The main idea can be the same, but the way it is executed is different. Both of the versions of this Bubble Sort are looping through the array items a lot of times (more than N times, where N is the number of items in the array). Both of the versions also have the same idea of bubble sort, which is: Comparing pair of elements and swap them in a way that on the end of each loop, the highest element will be in the end of the array. You can discover that by running the bubbleSortConcept2 on your browser, by running this: bubbleSortConcept2([5, 4, 3, 2, 1]). It will show you the resulting array after each loop, which is: An array that have the highest element on the end of it. This is the main idea of bubble sort and both algorithms are doing that!

2) Why do you callthem pointers? => Pointers doesn't exist only in C++ or C level. In fact, most part of the languages (or all of them) use pointers inside. Some very high-level languages (Java, Ruby, Python, R, ...) just hide that information to you, but it is using the pointers in the depths, since these high-level languages convert the code to a low-level language and they need to deal with pointers! C/C++ are considered high-level languages, but in a lower dimension than the ones I just mentioned, since C/C++ needs to make you deal pointers. I will try to be very succinct: Pointers are just variables that points to another variables. That's it. (In deep therms, it points to a memory address of another variable, but you can study more of that if you want). Now, let's go to the first sorting example... The i and the j variables are pointers, because they points to the position (index) of an element in the array. :) On the second sorting example, the index is the pointer, for the same reason.

3) Also I didn't understand what o(n2) meant => Yeah, that is a bit complex to explain to you, as it envolves the core of Algorithm Analysis, haha, but I will try. The N is the array length, as you noticed. The algorithm loop through the array length more than N times, the question is: Can you figure out how many comparisons (if's) this algorithm will have on the total? This will show the nature of the bubble sort. You can check the quantity of comparisons by adding this `comparisonCount` here...

``````function bubbleSortConcept1(arr) {
var comparisonCount = 0

for (let j = arr.length - 1; j > 0; j--) {
for (let i = 0; i < j; i++) {
comparisonCount++
if (arr[i] > arr[i + 1]) {
let temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
}
}

console.log('N (length): ', arr.length)
console.log('Comparisons: ', comparisonCount)
}
``````

Here are some results:

``````bubbleSortConcept1([2, 1])
N (length): 2
Comparisons: 1

bubbleSortConcept1([3, 2, 1])
N (length): 3
Comparisons: 3

bubbleSortConcept1([4, 3, 2, 1])
N (length): 4
Comparisons: 6

bubbleSortConcept1([5, 4, 3, 2, 1])
N (length): 5
Comparisons: 10

bubbleSortConcept1([6, 5, 4, 3, 2, 1])
N (length): 6
Comparisons: 15

bubbleSortConcept1([7, 6, 5, 4, 3, 2, 1])
N (length): 7
Comparisons: 21

bubbleSortConcept1([20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1])
N (length):  20
Comparisons:  190
``````

As you can see, the quantity of Comparisons is growing much more faster than the N (length), this indicates that the order of magnitude of this algorithm is greater than N, now you need to find the order of magnitude in which the Comparisons is greater than the N (length).
You need to find the equation that gives you the quantity of Comparisons based on the N (length). On the bubble sort, this equation is:

``````c = n(n - 1)/2
``````

You can verify it applying to different examples, let's take the last one...

``````bubbleSortConcept1([20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1])
N (length):  20
Comparisons:  190

// Replacing it on the equation you found...
c = 20(20 - 1)/2
c = 20(19)/2
c = 380/2
c = 190
// 190 comparisons
``````

Now, why it is O(n^2) after all of this explanation?
`n(n - 1)/2` is the same as: `(n^2 - n)/2`.
You need to study what is the O notation / Big O notation to enter on the details, but, in summary, you need to extract the function that grows faster on this equation: `(n^2 - n)/2`.

n^2 grows faster than n ? Yes! So it is O(n^2)

Aslan French

Thank you, this was super helpful! Your explanation of how n2 works was in particular useful.

Emma Bostian ✨

This goes back to the principles of computer science, so you might want to read up on those principles if you're confused.

There are many different ways to write code, there's never just one answer.

Pointers are just that; pointers to a spot in an array. They keep track of the index we're at. I could have called them anything as they're just variables.

O(N2) refers to the run time. Because we're comparing every element with every other element, and Big-O refers to the worst-case scenario or upper-bound, the most comparison's you'll have to do is N * N.

Aslan French

Thanks. Reading up on those basics is a big part of what I've been trying to do lately, one reason why I found your article. Thanks!

Jeremy Moore

I was curious as to what sorting algorithm JavaScript uses, and apparently there's no universal specification. Different browsers seem to use different algorithms.

bugzilla.mozilla.org/show_bug.cgi?...

Super cool Emma!
I want also to point to a bubble sort visualizer built in JavaScript.

codeguppy.com/code.html?visual_sort

Pablo Yev

Did you create this content?? It was very clear and right now I am looking for references just like this. Thanks!

Emma Bostian ✨

Haha yes I created it. Why would I post it if I hadn't? :P

Pablo Yev

You are right!! What I meant was if all the material was made by you or you got it from a book or something. I'm a visual learner and the way you presented the info was very clear for me.

Emma Bostian ✨

Ahh yeah haha I see. No I create them all myself using Sketch :)

David Sima

I'm sure that this is very good content for the beginners! Good job with this one :) Waiting for the next one.

memon shoyeb

Loved this ! great explanation emma !!

João Ferreira • Edited

Thank you but... aaammm... what else. I'm curious if there are some green solutions.

Unfortunately there aren’t any green solutions for sorting an array.

This seems kind of inefficient at first but if you think about it it kind of makes sense. Best case scenario an array is already sorted, which logically still takes N steps since you have to walk through each element of the array to know it’s sorted.

But usually the array won’t be sorted, which means you still have to take N steps, plus even more steps to actually do the work of sorting the array, which is where we get second N in O(N2).

You can do better than N2 by using certain algorithms like merge sort, but even then you’re still limited by the fact that you have to touch every element at least once, plus you have to take extra steps to reorganize the content of the array, and it turns out the most efficient way you can do this is in O(N log N) time.

Didn't run/test yet but has the doubt in Concept 2 Code: what about arr[index + 1] when at the last item is coming in the iteration.. will it be array index out bounds ?