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
Merge sort is a divide-and-conquer sorting algorithm. It works by continuously splitting the list in half until each sublist contains just one item, then merging those sublists back together in the correct order. It is faster than bubble sort for large datasets but uses more memory due to the temporary sublists created during the process.
def merge_sort(data):
if len(data) <= 1:
return data
mid = len(data) // 2
left = merge_sort(data[:mid])
right = merge_sort(data[mid:])
return merge(left, right)
def merge(left, right):
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result += left[i:]
result += right[j:]
return result
print(merge_sort([6, 2, 7, 1]))
# Output: [1, 2, 6, 7]