Algorithm - Bubble sort

A sort is used to arrange elements in an array into either ascending or descending order.

In a bubble sort the elements are compared in pairs and swapped if necessary. In this way, the larger of the pair ‘bubbles’ towards one end of the array. After each pass one more element will have moved to its correct position in the array.

It should be stressed that bubble sort is the slowest sorting algorithm and should not be used as a sorting method in a final piece of software. You do need to understand it though.

This video demonstrates how bubble sort works, it also shows an algorithm which is different to the one below. This is an important concept to understand about algorithms, they can and will be different. There are often multiple solutions to a problem, therefore there are multiple different algorithms.

The following algorithm sorts an array of names into ascending order.

BEGIN BubbleSort
  Let Last = number of names in the array
  Let Swapped = true
  WHILE Swapped = true
    Let Swapped = false
    Let i = 1
    WHILE i < Last
      IF Name (i) > Name (i+1) THEN
        Swap (Name (i), Name (i+1))
        Let Swapped = true
      ENDIF
      Increment i
    ENDWHILE
    Decrement Last
  ENDWHILE
END BubbleSort

When BubbleSort calls the subroutine Swap, the parameters passed are Name (i) and Name (i+1). In the subroutine Swap, more general names (A and B) are used for the parameters. This allows this swap routine to be used for swapping any two variables.

Note: Assuming that the array is declared as a global variable, any changes made to the array in this Swap routine will be reflected in the array as seen and used by all routines.

BEGIN Swap (A, B)
  Let Temp = A
  Let A = B
  Let B = Temp
END Swap

Comments

comments powered by Disqus