Professional Documents
Culture Documents
CMPT128
CMPT128
CMPT128
In this Week
Merge Sort Algorithm
Additional Material (C++ file Input/Output)
Review of the course
Merge Sort
In merge sort algorithm, the sorting procedure
goes as follows:
Algorithm Merge Sort
Sort the left half of the array
Sort the right half of the array
Combine (or merge) the left half and the right half
of the array
Details follow
CMPT 128 - FIC 2015-02 - Yonas T.
Weldeselassie
Merge Sort
We can use any sorting algorithm to sort the
left half and the right half of the array
However, it makes sense by just looking at the
algorithm that we can make a recursive call of
the same algorithm
The stopping criteria will be when there is no
element to sort or there is only one element
to sort which is already sorted anyways
CMPT 128 - FIC 2015-02 - Yonas T.
Weldeselassie
Merge Sort
The C++ code for merge sort algorithm will be
Merge Sort
The merge function takes an array A such that
the elements
A[startIndex], A[startIndex+1],....,A[middleIndex]
Merge Sort
In combining (merging) the left half and right
half sub-arrays therefore, we should proceed
as follows
Make a temporary array of the same size
While both sub-arrays have elements, copy
smallest element of the two sub-arrays to the
temporary array. Delete the smallest element
from its sub-array
Copy any remaining elements from whichever left
half that still has elements left
CMPT 128 - FIC 2015-02 - Yonas T.
Weldeselassie
Merge Sort
We notice that we don't have to search for the
smallest element of the two sub-arrays
Since the sub-arrays are sorted, the smallest
element must be either A[startIndex] or
A[middleIndex+1]
This is the heart of the merge sort algorithm.
We can merge the sorted sub-arrays efficiently
Why merge on temporary array?
CMPT 128 - FIC 2015-02 - Yonas T.
Weldeselassie
Merge Sort
We should merge the sub-arrays to temporary
array for otherwise we will destroy the array
being merged
Of course one could merge in the same array
with additional tasks. Can you think how?
The C++ function for the merging algorithm
follows:
Merge Sort
Merge Sort
10
11
12
13
14
15
16
17
18
19
20
21
Lab Work
Write a program that creates a new output file named
RandomIntegers.txt and will fill it with 20 random
integers in the range [-50, 50]
Write a program that will create a dynamic array of size
20 and populates the array with the random integers
contained in the file RandomIntegers.txt
Write a program that will create a dynamic array of size
20 and populates the array with the random integers
contained in the file RandomIntegers.txt; sorts the array
using merge sort algorithm and then writes the sorted
integers to an output file named SortedIntegers.txt
Write a program that will read each integer contained in
the file SortedIntegers.txt and prints it to the screen
CMPT 128 - FIC 2015-02 - Yonas T.
Weldeselassie
22