JavaScript – Bubble Sort

GitHub Code

While working on an unrelated blog post, I found I was in quick need of a sorting algorithm. So, I pulled out my old friend the bubble sort.  Undoubtedly there are better sorting algorithms (quick sort comes to mind), but this is the one I always think of first.  Not because it is a blazing fast algorithm or especially clever, but because it is simple to remember.  I am not sure how others feel, but given all the technical things I ‘stuff’ into my head each day, the simpler things come to mind first 🙂

Also, as I continue my JavaScript ‘schooling’ from my .NET upbringing, I will be adding other sorting algorithms like the patterns I have been adding here.

On to the bubble sort!

To run:
▪    Make GET call

Screen Shot 2017-05-29 at 9.50.09 AM

▪    View results

Screen Shot 2017-05-29 at 9.50.55 AM

As mentioned earlier, bubble sorts are not the fastest algorithms out there.  If I had to pick for performance, a quick sort is at the top of my list.  However, quick sorts (subject of a future post) are not as simple as the bubble sort.  With an O notation of roughly O (n2) (reference #1), most implementations (mine does) has two loops – an outer and an inner.  The outer loop’s job is to guarantee that each array position has a chance to ‘bubble’ through the array.  The inner loop’s job is to compare neighboring elements and if the one before is bigger, flip their position.

Screen Shot 2017-05-29 at 9.51.44 AM

Stay tuned!





Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s