Bubble sort
An example of a sorting algorithmA sequence of logical instructions for carrying out a task. In computing, algorithms are needed to design computer programs. 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:
- Look at the first number in the list.
- Compare the current number with the next number.
- Is the next number smaller than the current number? If so, swap the two numbers around. If not, do not swap.
- Move to the next number along in the list and make this the current number.
- Repeat from step 2 until the last number in the list has been reached.
- If any numbers were swapped, repeat again from step 1.
- 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 loopThe repetition of an activity within a computer program. 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 pseudocode Also written as pseudo-code. A method of writing up a set of instructions for a computer program using plain English. This is a good way of planning a program before coding., 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