Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

ALGO COMPLEXITY MODULE 3 Lesson 7

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

18

Lesson 7

 MERGE SORT

Merge Sort

We now turn our attention to using a divide and conquer strategy as a


way to improve the performance of sorting algorithms.

Merge sort is a recursive algorithm that continually splits a list in half.


If the list is empty or has one item, it is sorted by definition (the base case).
If the list has more than one item, we split the list and recursively invoke a
merge sort on both halves. Once the two halves are sorted, the fundamental
operation, called a merge, is performed. Merging is the process of taking two
smaller sorted lists and combining them together into a single, sorted, new
list. Figure 5 shows our familiar example list as it is being split by merge sort.
Figure 6 shows the simple lists, now sorted, as they are merged back together.

The process of merging two sorted lists together is O(n). Merge sort,
effectively, does this O(log n) times because it splits the list in half at every
step. So, that makes the overall efficiency O(n log n).

Fig 5. Splitting the List in a Merge Sort

Module III
19

Fig 6. Lists as they are Merged Together

Algorithm
The algorithm works as follows:
1. Divide the array in half.
2. Recursively sort both halves.
3. Merge the halves back together.

Sample Implementation

Module III
20

1. Given the following list of numbers:


[21, 1, 26, 45, 29, 28, 2, 9, 16, 49, 39, 27, 43, 34, 46, 40]
Which answer illustrates the list to be sorted after 3 recursive calls to
mergesort?

A. [16, 49, 39, 27, 43, 34, 46, 40]


B. [21,1]
C. [21, 1, 26, 45]
D. [21]

2. Given the following list of numbers:


[21, 1, 26, 45, 29, 28, 2, 9, 16, 49, 39, 27, 43, 34, 46, 40]
Which answer illustrates the first two lists to be merged?

A. [21, 1] and [26, 45]


B. [[1, 2, 9, 21, 26, 28, 29, 45] and [16, 27, 34, 39, 40, 43, 46, 49]
C. [21] and [1]
D. [9] and [16]

Module III

You might also like