Sorting Algorithms
Sorting Algorithms
27/02/2024
Sorting Algorithms – Bubble and Merge Sorts
Starter:
1) The purpose of a sorting algorithm is to rearrange items in a particular order, such as
alphabetical or numerical. Throughout the process, it will make use of sequence,
selection, assignment, and iteration. Selection is used in order to move items around,
such as the item with the smallest value being moved to the front in ascending order.
Assignment is used to reassign values to variables. Sequence is used to conduct the
operations in a specific order. Iteration is used to repeat the prior process to reach
the desired collection order.
2) A third ‘temporary variable’ is needed to swap/switch two variables because it
prevents losing any variables. For instance, the data of the first variable would be
assigned to the temporary variable. This then allows for the second variable’s data to
be moved onto the first then placing the original first data onto the second.
3) A ‘flag variable’ can be used so it can be flagged up only when a swap is needed.
Bubble Sort
1. Overview:
Bubble sort algorithms involve comparing individual items in a list with the
item next to it and then making swaps based on certain conditions. For
instance, if the item has a larger value. This process would iterate until
there are no more swaps needed; the list is in a correct order.
2. Time Efficiency:
An advantage of this is that it is simple to conduct. However, compared to other sorting
algorithms, bubble sorts are less efficient as it requires many more passes. This therefore
makes it more suited for smaller databases. It has a time complexity of O(n 2)
3. Pseudocode:
function bubble_sort(list):
swapped = True
while swapped:
swapped = False
for i in range(len(list) - 1):
if list[i] > list[i + 1]:
list[i], list[i + 1] = list[i + 1], list[i] # Swap elements
swapped = True
4. Python Code:
Emmanuel Kumi
Merge Sort:
1. Overview:
Merge sorts involves breaking down the list into smaller pieces, until they are singular. The
algorithm then 'merges' adjacent elements until the list is sorted.
2. Time Efficiency:
Compared to the bubble sort, it is a lot more efficient with larger
databases. It has a time complexity of O(n log n)
3. Pseudocode:
function merge_sort(list):
if len(list) <= 1:
return list
mid = len(list) // 2
left = merge_sort(list[:mid])
right = merge_sort(list[mid:])
return merge(left, right)
4. Python Code:
Emmanuel Kumi
Exam Questions:
(a) A bubble sort involves comparing individual elements of a list and then making
swaps based on certain criteria. Multiple passes are conducted, as the sort iterates
until completion.
(b) Sequence after first pass :
3, 5, 8, 12, 15, 17, 18, 1, 23
(c) It takes two passes.
Emmanuel Kumi
1-2-3-4-5-6-7-8