Algorithms Worksheet 4 Merge Sort and Quickso
Algorithms Worksheet 4 Merge Sort and Quickso
Unit 12 Algorithms
Sophie
Amelia
Poppy
Olivia
Ava
Lily
Isla
Read a card from each pair and write the lower value name to the merged list of 2 items
Then write the other value to the merged list
Do this for each pair
Fill in the names below. The first two pairs have been done for you.
Jessica
Sophie
Amelia
Poppy
Olivia
Ava
Lily
Isla
Sophie
Amelia
Poppy
Olivia
Ava
Lily
Isla
1
Worksheet 4 Merge sort and quick sort
Unit 12 Algorithms
Am Jes So
Oli Po
Ava Isla sic Lily phi
elia va ppy
a e
Task 2
An algorithm for the Merge sort is given on the next page.
In this task you will focus on the merge phase of the process (enclosed by a border in the
pseudocode below) in which the two sorted sublists are merged into one sorted list.
Complete the trace table below to show how two lists called lefthalf and righthalf are merged
into the sorted list alist.
lefthalf = [1, 3, 9] righthalf = [4, 6, 8]
1 3 9 4 6 8
i=0 j=0
k=0
len
len lefthalf[i
(lefthalf i j k righthalf[j] alist[k]
(righthalf) ]
)
3 3 0 0 0 1 4 [1]
procedure mergeSort(alist)
if len(alist) > 1
mid = len(alist) div 2 # performs integer division
lefthalf = alist[:mid] # left half of alist put into
lefthalf
righthalf = alist[mid:] # right half of alist put into
righthalf
mergeSort(lefthalf)
mergeSort(righthalf)
2
Worksheet 4 Merge sort and quick sort
Unit 12 Algorithms
i = 0
j = 0
k = 0
while i < len(lefthalf) and j < len(righthalf)
if lefthalf[i] < righthalf[j]
alist[k] = lefthalf[i]
i = i + 1
else
alist[k] = righthalf[j]
j = j + 1
endif
k = k + 1
endwhile
#check if the left half still has elements not merged
#if so, add them to alist
while i < len(lefthalf)
alist[k] = lefthalf[i]
i = i + 1
k = k + 1
endwhile
#check if the right half still has elements not merged
#if so, add them to alist
while j < len(righthalf)
alist[k] = righthalf[j]
j = j + 1
k = k + 1
endwhile
print("Merged sublist ",alist)
endif
endprocedure
3
Worksheet 4 Merge sort and quick sort
Unit 12 Algorithms
The left pointer moves right until it finds an item larger than the pivot, then stops.
The right pointer moves left until it finds an item smaller than the pointer, and then
stops.
The value at the left pointer is swapped with the value at the right pointer.
The pointers resume moving, swapping items until the left pointer crosses the right
pointer.
The pivot is then swapped with with the value at the right pointer and is now in the
correct position.
34 56 23 81 28 66 35 17 88 37 18 50
P L R
34 56 23 81 28 66 35 17 88 37 18 50
P L R
34 50
34 50
34
4
Worksheet 4 Merge sort and quick sort
Unit 12 Algorithms
Task 4
https://www.cs.usfca.edu/~galles/visualization/ComparisonSort.html
or
https://www.youtube.com/watch?v=ZZuD6iUe3Pc