Sorting Algorithms: Bubble Sort

    Sorting Algorithms: Bubble Sort

      So you're in the market for a good sorting algorithm, huh? If you love making comparisons and don't mind waiting around for the answer, BubbleSort's a great option.

      The algorithm looks like this:

      BUBBLESORT(List L):
      	LET n equal the length of L:
      	FOR i from 0 to n:
      		FOR j from 0 to ni:
      			IF L[j] > L[j + 1]:
      				SWAP L[j] and L[j + 1]

      Whoa, wait, where are you going? Come back: we'll show you what it means.

      Take the following list, where the first row tells the index and the second row tells the value:

      01234
      54721

      The sort starts by looking at the first two numbers. If the one on the left is bigger than the one on the right (spoiler alert: it is), then they swap places:

       

      Then it moves one place to the right, and compares index 1 with index 2.

       

      Since 5 is less than 7, nothing happens. Now it compares index 2 with index 3.

       

      You know the deal. 2 is less than seven, so:

       

      The result?

       

      An unsorted list. But we've found the largest number in the list and moved it to the end.

      #NotAsUnsortedAsItCouldBe

      If we continue this for another round, the list looks like this:

       

      Which means we've found the second largest element. See what we did there?

       

      Every time we go through the list, we find the next largest element, so that by the time we've made 4 – 1 rounds of comparisons, the list is sorted.

       

      Every round of sorting makes the next largest element "bubble" to the end. It's almost like they named the sort with that metaphor in mind.

      Because we have two nested for loops, this sort takes O(n2) time, making it less-than-efficient in sorting terms. It isn't bad, but we can do better. That might not matter for a list of size five, but if we have a list of size 1,000 it's huge. There really isn't any reason to use Bubble Sort except for the fact that bubbles are awesome.