/Talk |

The bubble sort algorithm is:

- compare adjacent elements. If the first is greater than the second, swap them.
- do this for each pair of adjacent elements, starting with the first two and ending with the last two. At this point the last element should be the greatest (it has "bubbled" to the top).
- repeat the steps for all elements except the last one.
- keep repeating for one fewer element each time, until you have no more pairs to compare.

A simple implementation of bubble sort in Python:

def bubblesort(array, cmp = lambda x, y: x > y): for i in range( len(array) ): for j in range( len(array)-1-i ): if cmp(array[j], array[j+1]): ( array[j], array[j+1] ) = ( array[j+1], array[j] )

Or in the C programming language:

void bubbleSort(int *array, int length) { int i, j; for(i = length - 1; i > 0; i--) for(j = 0; j < i; j++) if(array[j] > array[j+1]) /* compare neighboring elements */ { int temp; temp = array[j]; /* swap array[j] and array[j+1] */ array[j] = array[j+1]; array[j+1] = temp; } }

/Talk