大象传媒

Bubble sort

An example of a sorting is bubble sort. This is a simple algorithm used for taking a list of unordered numbers and putting them into the correct order.

Each run through the list, from start to finish, is known as a pass. The bubble sort continues until a pass is made where no values have been swapped. At this point, the list is sorted.

The algorithm runs as follows:

  1. Look at the first number in the list.
  2. Compare the current number with the next number.
  3. Is the next number smaller than the current number? If so, swap the two numbers around. If not, do not swap.
  4. Move to the next number along in the list and make this the current number.
  5. Repeat from step 2 until the last number in the list has been reached.
  6. If any numbers were swapped, repeat again from step 1.
  7. If the end of the list is reached without any swaps being made, then the list is ordered and the algorithm can stop.

Bubble sort example

This algorithm could be used to sort the following list:

27, 4, 7, 12, 9

The first of the algorithm would produce:

4, 27, 7, 12, 9 (4<27 so the two values are swapped)

4, 7, 27, 12, 9 (7<27 so the two values are swapped)

4, 7, 12, 27, 9 (12<27 so the two values are swapped)

4, 7, 12, 9, 27 (9<27 so the two values are swapped)

4, 7, 12, 9, 27 (first pass completed - 27 has 鈥榖ubbled鈥 to the top of the list)

Values were swapped so the algorithm needs to run again. The second loop of the algorithm would start with the final list and run again as follows:

4, 7, 12, 9, 27 (4<7 so the values are not swapped)

4, 7, 12, 9, 27 (7<12 so the values are not swapped)

4, 7, 9, 12, 27 (9<12 so the values are swapped)

4, 7, 9, 12, 27 (12<27 so the values are not swapped)

4, 7, 9, 12, 27 (second pass completed)

Values were swapped so the algorithm needs to run again. This time there will be no swaps as the values are in order:

4, 7, 9, 12, 27

The algorithm has completed a pass without swapping anything and it knows that the list is now ordered and can stop.

In , this would look like:

counter <-- 0
swaps <-- 1
length <-- LEN(list)# this gives the number of elements in the array

WHILE swaps > 0
     swaps <-- 0
     FOR counter <-- 0 TO length-2 DO
          IF list[counter] > list[counter+1] THEN
                temp <-- list[counter]
                list[counter] <--list[counter+1]
                list[counter+1] <-- temp
                swaps <-- swaps + 1          聽聽聽聽聽聽聽聽聽聽
          ENDIF
     ENDFOR
ENDWHILE

Sorting a list using the bubble sort algorithm