Back to home

Bubble Sort: How To Trace







Bubble sort is sorting techniques that mimic bubbles. The idea is when you
sort in ascending order, the smaller data will "bubble up" to the lower
index -- or alternatively -- the larger data will "sink down" to the larger
index.

Try to step through the trace below with the bubble sort algorithm (that
looks something like this):
  For i := 1 To maxarray - 1 do
      For j := i + 1 to maxarray do
          If a[i] > a[j] Then
          begin
              temp := a[j];
              a[j] := a[i];
              a[i] := temp;
          End;

Starting:
	7 3 5 6 2         : maxarray = 5, i = 1
		Look into the loop j:
		j = 2:  a[i] > a[j]? ==> a[1] > a[2]? ==> 7 > 3, so swap: 3 7 5 6 2
		j = 3:  a[i] > a[j]? ==> a[1] > a[3]? ==> 3 > 5, no swap
		j = 4:  a[i] > a[j]? ==> a[1] > a[4]? ==> 3 > 6, no swap
		j = 5:  a[i] > a[j]? ==> a[1] > a[5]? ==> 3 > 2, so swap: 2 7 5 6 3
	[2] 7 5 6 3       : i = 2
		Look into the loop j:
		j = 3:  a[i] > a[j]? ==> a[2] > a[3]? ==> 7 > 5, so swap: 2 5 7 6 3
		j = 4:  a[i] > a[j]? ==> a[2] > a[4]? ==> 5 > 6, no swap
		j = 5:  a[i] > a[j]? ==> a[2] > a[5]? ==> 5 > 3, so swap: 2 3 7 6 5
	[2 3] 7 6 5       : i = 3
		Look into the loop j:
		j = 4:  a[i] > a[j]? ==> a[3] > a[4]? ==> 7 > 6, so swap: 2 3 6 7 5
		j = 5:  a[i] > a[j]? ==> a[3] > a[5]? ==> 6 > 5, so swap: 2 3 5 7 6
      [2 3 5] 7 6       : i = 4;
		Look into the loop j:
		j = 5:  a[i] > a[j]? ==> a[4] > a[5]? ==> 7 > 6, so swap: 2 3 5 6 7
	[2 3 5 6 7]
      We're done!

Well, you can observe that smaller data is bubbling up. This is some sort of
bubble sort (but not the original version). This version (i.e. mine) is a
lot easier to remember.


Back to home


Roby Joehanes, © 2001