DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Reversing an Array: An Exploration of Array Manipulation
  • Unlocking the Potential of Binary Search Trees with C# Programming
  • Sliding Window
  • Arrays and Hashing. Vol.2

Trending

  • On-Device Debugging and JUnit 5
  • Operationalizing Enterprise AI at Scale: Architecture, Governance, and Adoption
  • Reducing RAG Hallucinations With Relationship-Aware Retrieval
  • Introducing RAI Audit Kit: Evidence-Grade Responsible AI Audits in Python
  1. DZone
  2. Data Engineering
  3. Data
  4. What Is Bubble Sort?

What Is Bubble Sort?

Bubble sort is probably the simplest sorting algorithm. It is inefficient at scale, but quick to write and works fine on a handful of elements.

By 
Dave Saunders user avatar
Dave Saunders
·
Apr. 22, 21 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
6.7K Views

Join the DZone community and get the full member experience.

Join For Free

Why Should I Care?

Bubble sort is an excellent introduction to sorting algorithms.

It is also useful as a reference when we cover more complex search algorithms later.

In 5 Minutes or Less

Let's sort this array into ascending order:

Step 1: Compare Pairs of Elements

We're going to loop through each pair of elements in turn.

If a pair of elements aren't in the right order, we'll swap them.

Let's go...

The first pair is already in the correct order, so we can ignore them.

On to the next pair. These elements are in the wrong order, so we'll swap them.

And finally the last pair, which also need to be swapped:

We've now looped through all of the pairs, so our first pass through the array is done.

This is how the array looked at the beginning and end of this first pass:

Notice how the highest value, 9, moved up through the array and into the correct place:

It has 'bubbled up' to the correct position - hence 'Bubble Sort.'

Step 2: Repeat

Our first pass moved the highest element, 9, into the correct place.

Each time we repeat this loop, we move the next highest element into place.

Now, we repeat this process – comparing each pair in-turn and swapping them if required – until the array is completely sorted.

We have four elements in the list, which means we'll need to repeat our loop three times.

Why three? Because once three of the elements are in the correct place in the array, the remaining one must also be correct.

If the number of elements in our array is n, the number of loops we'll need is n-1.

Here's the state of our array after each pass. The sorted elements after each loop are highlighted.

Here's the JavaScript code for this algorithm:

JavaScript
 




x
13


 
1
// We need to repeat the algorithm n-1 times
2
for (let loop = 0; loop < array.length - 1; loop++) {
3

          
4
    // Loop through each pair of elements
5
    for (let pair = 0; pair < array.length - 1; pair++) {
6

          
7
        // Is this pair the wrong way around?
8
        if (array[pair] > array[pair + 1]) {
9
            // Make the swap (using temporary variable)
10
            let tmp = array[pair]
11
            array[pair] = array[pair + 1]
12
            array[pair + 1] = tmp
13
        }    } }


View on JSFiddle

We can improve on this basic algorithm though, with a couple of optimizations.

Optimization #1

Remember how the first pass of the algorithm caused the 9 to bubble up into the correct position?

After that first pass, we know that the last element is correctly placed, so we can ignore it on our next loop. After the second pass, the second-to-last element is sorted, and so on.

We'll change our code to ignore the last element after the first loop, the last two after the second loop, and so on.

This will make our algorithm slightly quicker.

Here's the updated code. Notice that the limit for the inner loop is now array.length - loop - 1:

JavaScript
 




xxxxxxxxxx
1
10
9


 
1
for (let loop = 0; loop < array.length - 1; loop++) {
2
    for (let pair = 0; pair < array.length - loop - 1; pair++) {
3
        if (array[pair] > array[pair + 1]) {
4
            let tmp = array[pair]
5
            array[pair] = array[pair + 1]
6
            array[pair + 1] = tmp
7
        }    
8
    }
9
}


View on JSFiddle

Optimization #2

Imagine our algorithm was passed an array like this:

This array is already sorted, doing three loops of our sorting algorithm is a complete waste of time.

This leads us to our next optimization; if we ever complete a loop without swapping any elements, we know the array is sorted and we can stop early.

That could be a big time saving when the array is already sorted – or nearly sorted – before we even start our Bubble Sort.

With that code added, our final Bubble Sort algorithm looks like this:

JavaScript
 




xxxxxxxxxx
1
15


 
1
for (let loop = 0; loop < array.length - 1; loop++) {
2

          
3
    let hasSwapped = false;
4

          
5
    for (let pair = 0; pair < array.length - loop - 1; pair++) {
6
        if (array[pair] > array[pair + 1]) {
7
            let tmp = array[pair]
8
            array[pair] = array[pair + 1]
9
            array[pair + 1] = tmp
10
            hasSwapped = true;
11
        }    } 
12
    if (!hasSwapped) {
13
        // No swaps, the array is now sorted
14
        break;
15
    } 
16
}


View on JSFiddle

Want to Know More?

Check out these links:

  • A visual representation of bubble sort
  • A more detailed article about the improvements mentioned above
Sort (Unix) Element Data structure Sorting algorithm

Published at DZone with permission of Dave Saunders. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Reversing an Array: An Exploration of Array Manipulation
  • Unlocking the Potential of Binary Search Trees with C# Programming
  • Sliding Window
  • Arrays and Hashing. Vol.2

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook