Data Structure: Bubble Sort?

What is a bubble sort technique?

Not the most efficient technique in terms of time complexity, but hey it can be optimized. The bubble sort technique, in a nutshell, is taking an array of adjacent items and comparing one to the next. If for any reason the items do not go from increasing order the element will be swapped.

How does it work

We can take an example array of [4,6,1,7,3,2,5]. We can start by iterating through the array.

for(let i = array.length - 1; i > 0; i--)

Notice how we are starting to decrementing instead of incrementing the array. This is because we want to decrement each time we go through an item.

Once the first iteration is established we can begin our second set of iteration. We won’t need to decrement. We can increment through each item like this.

for(let j = 0; j < array.length; j++)

Now it’s time to set our conditional statement. Our main purpose is to swap if the current item is greater than the next.

if(array[j] > array[j + 1])

Furthermore, we swap our items. And return the array. Here is a full solution below.

function bubbleSort(array){
for(let i = array.length - 1; i > 0; i--){
for(let j = 0; j < array.length; j++){
if(array[j] > array[j + 1]){
//swap and return array
let temp = array[j]
array[j] = array[j + 1]
array[j + 1] = temp
return array
//result [1, 2, 3, 4, 5, 6, 7]

What is the time complexity?

Given the fact we had to iterate twice the time complexity for this technique runs an O(n)² making it the worst-case scenario. However, it can be optimized.




Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to setup npm project for you and your team with automated formatting, linting, testing and more

React Native 0.63 Monorepo walkthrough

Weaponize JScript to bypass Windows Defender

Building context aware, stateful bots using Servo

Angular Basics -2

How to install Font awesome on Rails 6 APP

Deploy Angular 6 Application to Netlify

JavaScript Nuggets — Map

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Woodelin florveus

Woodelin florveus

More from Medium

Leap Before You Look, Write More Elegant Code

Guide To Dynamic Programming 👨‍💻

Simple steps to make a full-stack application.

How to be a great engineer!