Knowledge organisersSearching and sorting algorithms
Understand the main steps of each algorithm, Understand any pre-requisites of an algorithm, Apply the algorithm to a data set, Identify an algorithm if given the code or pseudocode for it
Bubble sort is a simple sorting algorithm that repeatedly goes through a list, comparing adjacent pairs of items and swapping them if they are in the wrong order. Each full pass through the list 'bubbles' the largest unsorted item to its correct position. The algorithm continues making passes until no swaps are needed, meaning the list is sorted.
def bubble_sort(data):
n = len(data)
for i in range(n - 1):
for j in range(n - 1 - i):
if data[j] > data[j + 1]:
data[j], data[j + 1] = data[j + 1], data[j]
return data
print(bubble_sort([3, 2, 9, 10, 7]))
# Output: [2, 3, 7, 9, 10]