Sorting Demos

Bubble Sort

Bubble sort is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The algorithm gets its name from the way smaller elements "bubble" to the top of the list. Because it only uses comparisons to operate on elements, it is a comparison sort. Although the algorithm is simple, most of the other sorting algorithms are more efficient for large lists. (Source: Wikipedia)

Need help?

The code below is an is one way of implementing a bubble sort. Read through it and try to fully understand each line! You can hover over each line for further explanation. The tricky part is understanding the constraints in the for loops! Use the graph to watch how bubble sorts work - comparing two elements at a time.

Note: In the graph, bList[j] is black and bList[j+1] is grey!

Psuedocode

Hover over lines of code for further explanation!
 
 bList = array of sortable items 

function bubbleSort(bList){
    for(int i = 1; i <= bList.length; i++){
        for(int j = 1; j <= bList.length-i; j++){
         //current value of i = 0, j =  0          
            if (bList[j] > bList[j+1])
                swapValueOf(bList[j], bList[j+1])
        }
    }
    return bList
}

Graph Visualization

Test your understanding! 1. Which line affects whether the list will sort in ascending or descending order?
Submit

Table of Values


Index	Value
1	8000
2	1492
3	2780
4	5000
5	702
6	2288
7	2022
8	6094
9	6973
10	153
11	347
12	4025
13	2517
14	6749
15	7507
16	1929