PcoWSkbVqDnWTu_dm2ix
We use cookies on this site to enhance your user experience

Jul 02 2018, 5:18 PM PST 2 min

The Bubble Sort is a Data Sorting algorithm. The bubble sort is a fairly simple sorting algorithm that will compare neighboring elements and switch them if needed. It has an average case complexity of O(n2).

Procedure

  1. Compare neighboring elements
  2. If the right side is smaller than the left, swap the elements
  3. repeat all the way down the list
  4. repeat until nothing is swapped

Example Code

--Sorting table tab
--repeat the loop until nothing is swapped
repeat 
    swapped = false
    --loop through the table from start to finish
    for i=2, #tab do
        --compare two neighboring elements
        if tab[i-1] > tab[i] then
            --swap them
            tab[i-1], tab[i] = tab[i], tab[i-1]
            swapped = true
        end
    end
until not swapped
Tags:
  • concept
  • coding
  • algorithms
  • sort