The Merge Sort Algorithm
The Merge Sort Algorithm
Sort Algorithms
www.computerscienceuk.com
GCSE 9-1: OCR Computer Science
www.computerscienceuk.com
GCSE 9-1: OCR Computer Science
Sorting Algorithms
Learning
Objectives: Sorting Algorithms
To understand…
www.computerscienceuk.com
GCSE 9-1: OCR Computer Science
Sorting Algorithms
Learning Merge Sort Algorithm
Objectives:
How it works:
To understand…
www.computerscienceuk.com
GCSE 9-1: OCR Computer Science
Sorting Algorithms
Learning Merge Sort Algorithm
Objectives:
How it works:
To understand…
www.computerscienceuk.com
GCSE 9-1: OCR Computer Science
Sorting Algorithms
Learning Merge Sort Algorithm
Objectives:
How it works:
To understand…
Standard Sorting
Algorithms: Continuing on from the
-merge sort previous slide… 1 2 6 8 3 5 4 7
…each pair of sorted
pairs are compared and 3
sorted into sorted sets of
4. 5 4 7
This is done by
continually comparing 3 4
the left most items in
each pair and adding the 5 7
smallest of these items
to a new list each time. 3 4 5
7
1 2 6 8 3 4 5 7
www.computerscienceuk.com
GCSE 9-1: OCR Computer Science
Sorting Algorithms
Learning Merge Sort Algorithm 1 2 6 8 3 4 5 7
Objectives: How it works:
1
To understand…
2 6 8 3 4 5 7
Standard Sorting Next, the items in each
Algorithms: pair of sorted 4s are 1 2
-merge sort compared and sorted into
sorted sets of 8. 6 8 3 4 5 7
This is done by 1 2 3
continually comparing
the left most items in 6 8 4 5 7
each pair and adding the
smallest of these items 1 2 3 4
to a new list each time.
6 8 5 7
1 2 3 4 5
Because this example 6 8 7
contained 8 numbers,
the data is sorted at the 1 2 3 4 5 6
end of this phase. For
longer data sets, the 8 7
process would continue
in the same manner.
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
www.computerscienceuk.com
GCSE 9-1: OCR Computer Science
Sorting Algorithms
Learning
Objectives: Merge Sort Algorithm
To understand… def mergeSort(dataSet):
result = []
Standard Sorting IF LENGTHOF(dataSet) < 2
Algorithms: RETURN x
-merge sort
mid = LENGTHOF(dataSet) DIV 2
y = mergeSort(x[:mid])
z = mergeSort(x[mid:])
i=0
j=0
WHILE i < LENGTHOF(y) and j < LENGTHOF(z):
IF y[i] > z[j]
result.APPEND(z[j])
j += 1
ELSE
result.APPEND(y[i])
i += 1
result += y[i:]
result += z[j:]
RETURN result
dataSet = [4,6,2,8,4,55,6,22,54,23,36,42]
results = mergeSort(dataSet)
DISPLAY results
www.computerscienceuk.com
GCSE 9-1: OCR Computer Science
Question
• Demonstrate all stages of a merge
sort so that the following set of data
can be ordered.
7 3 2 9 6 4 6 5
www.computerscienceuk.com
GCSE 9-1: OCR Computer Science
Answer 2 3 7 9 4 6 5 8
4
7 3 2 9 6 4 8 5 6 5 8
4 5
7 3 2 9 6 4 8 5
6 8
3 7 2 9 4 6 5 8
4 5 6
3 7 2 9 4 6 5 8 8
2 2 3 7 9 4 5 6 8
3 7 9 4 6 5 8
2 3
7 9 4 6 5 8
2 3 7
9 4 6 5 8
2 3 7 9
www.computerscienceuk.com
GCSE 9-1: OCR Computer Science
2 3 7 9 4 5 6 8
2
3 7 9 4 5 6 8
2 3
7 9 4 5 6 8
2 3 4
7 9 5 6 8
2 3 4 5
7 9 6 8
2 3 4 5 6
7 9 8
2 3 4 5 6 7
9 8
2 3 4 5 6 7 8
2 3 4 5 6 7 8 9
www.computerscienceuk.com