SlideShare a Scribd company logo
College of Computing & Information Technology
King Abdulaziz University
CPCS-204 – Data Structures I
Sorting:
Merge Sort
Sorting: Merge Sort page 2
© Dr. Jonathan (Yahya) Cazalas
Sorting: Merge Sort
 Problem with Bubble/Insertion/Selection Sorts:
 All of these sorts make a large number of
comparisons and swaps between elements
 As mentioned last class (while covering n2 sorts):
 Any algorithm that swaps adjacent elements can only
run so fast
 So one might ask is there a more clever way to
sort numbers
 A way that does not require looking at all these pairs
 Indeed, there are several ways to do this
 And one of them is Merge Sort
Sorting: Merge Sort page 3
© Dr. Jonathan (Yahya) Cazalas
Sorting: Merge Sort
 Merge Sort
 Conceptually, Merge Sort works as follows:
 If the “list” is of length 0 or 1, then it is already sorted!
 Otherwise:
1. Divide the unsorted list into two sub-lists of about half
the size
 So if your list has n elements, you will divide that list into two
sub-lists, each having approximately n/2 elements:
2. Recursively sort each sub-list by calling recursively
calling Merge Sort on the two smaller lists
3. Merge the two sub-lists back into one sorted list
 This Merge is a function that we study on its own
 In a bit…
Sorting: Merge Sort page 4
© Dr. Jonathan (Yahya) Cazalas
Sorting: Merge Sort
 Merge Sort
 Basically, given a list:
 You will split this list into two lists of about half the size
 Then you recursively call Merge Sort on each list
 What does that do?
 Each of these new lists will, individually, be split into two lists
of about half the size.
 So now we have four lists, each about ¼ the size of the
original list
 This keeps happening…the lists keep getting split into
smaller and smaller lists
 Until you get to a list of size 1 or size 0
 Then we Merge them into a larger, sorted list
…which is sorted!
Sorting: Merge Sort page 5
© Dr. Jonathan (Yahya) Cazalas
Sorting: Merge Sort
 Merge Sort
 Incorporates two main ideas to improve its
runtime:
1) A small list will take fewer steps to sort than a
large list
2) Fewer steps are required to construct a sorted
list from two sorted lists than two unsorted lists
 For example:
 You only have to traverse each list once if they’re already
sorted
Sorting: Merge Sort page 6
© Dr. Jonathan (Yahya) Cazalas
Sorting: Merge Sort
 Merge function
 The key to Merge Sort: the Merge function
 Given two sorted lists, Merge them into one
sorted list
 Problem:
 You are given two arrays, each of which is already
sorted
 Your job is to efficiently combine the two arrays into one
larger array
 The larger array should contain all the values of the two
smaller arrays
 Finally, the larger array should be in sorted order
Sorting: Merge Sort page 7
© Dr. Jonathan (Yahya) Cazalas
Sorting: Merge Sort
 Merge function
 The key to Merge Sort: the Merge function
 Given two sorted lists, Merge them into one
sorted list
 If you have two lists:
 X (x1<x2<…<xm) and Y (y1<y2<…<yn)
 Merge these into one list: Z (z1<z2<…<zm+n)
 Example:
 List 1 = {3, 8, 9} and List 2 = {1, 5, 7}
 Merge(List 1, List 2) = {1, 3, 5, 7, 8, 9}
Sorting: Merge Sort page 8
© Dr. Jonathan (Yahya) Cazalas
Sorting: Merge Sort
 Merge function
 Solution:
 Keep track of the smallest value in each array that
hasn’t been placed, in order, in the larger array yet
 Compare these two smallest values from each array
 One of these MUST be the smallest of all the values in both
arrays that are left
 Place the smallest of the two values in the next location in
the larger array
 Adjust the smallest value for the appropriate array
 Continue this process until all values have been placed
in the large array
Sorting: Merge Sort page 9
© Dr. Jonathan (Yahya) Cazalas
3 10 23 54 1 5 25 75
X: Y:
Result:
 Example of Merge function:
Sorting: Merge Sort
Sorting: Merge Sort page 10
© Dr. Jonathan (Yahya) Cazalas
3 10 23 54 5 25 75
1
X: Y:
Result:
 Example of Merge function:
Sorting: Merge Sort
Sorting: Merge Sort page 11
© Dr. Jonathan (Yahya) Cazalas
10 23 54 5 25 75
1 3
X: Y:
Result:
Sorting: Merge Sort
 Example of Merge function:
Sorting: Merge Sort page 12
© Dr. Jonathan (Yahya) Cazalas
10 23 54 25 75
1 3 5
X: Y:
Result:
Sorting: Merge Sort
 Example of Merge function:
Sorting: Merge Sort page 13
© Dr. Jonathan (Yahya) Cazalas
23 54 25 75
1 3 5 10
X: Y:
Result:
Sorting: Merge Sort
 Example of Merge function:
Sorting: Merge Sort page 14
© Dr. Jonathan (Yahya) Cazalas
54 25 75
1 3 5 10 23
X: Y:
Result:
Sorting: Merge Sort
 Example of Merge function:
Sorting: Merge Sort page 15
© Dr. Jonathan (Yahya) Cazalas
54 75
1 3 5 10 23 25
X: Y:
Result:
Sorting: Merge Sort
 Example of Merge function:
Sorting: Merge Sort page 16
© Dr. Jonathan (Yahya) Cazalas
75
1 3 5 10 23 25 54
X: Y:
Result:
Sorting: Merge Sort
 Example of Merge function:
Sorting: Merge Sort page 17
© Dr. Jonathan (Yahya) Cazalas
1 3 5 10 23 25 54 75
X: Y:
Result:
Sorting: Merge Sort
 Example of Merge function:
Sorting: Merge Sort page 18
© Dr. Jonathan (Yahya) Cazalas
Sorting: Merge Sort
 Merge function
 The big question:
 How can we use this Merge function to sort an entire,
unsorted array?
 This function only “sorts” a specific scenario:
 You have to have two, already sorted, arrays
 Merge can then “sort” (merge) them into one larger
array
 So can we use this Merge function to somehow sort a
large, unsorted array???
 This brings us back to Merge Sort
Sorting: Merge Sort page 19
© Dr. Jonathan (Yahya) Cazalas
Sorting: Merge Sort
 Merge Sort
 Again, here is the main idea for Merge Sort:
1) Sort the first half of the array, using Merge Sort
2) Sort the second half of the array, using Merge
Sort
 Now, we do indeed have a situation where we can use
the Merge function!
 Each half is already sorted!
3) So simply merge the first half of the array with
the second half.
 And this points to a recursive solution…
Sorting: Merge Sort page 20
© Dr. Jonathan (Yahya) Cazalas
Sorting: Merge Sort
 Merge Sort
 Conceptually, Merge Sort works as follows:
 If the “list” is of length 0 or 1, then it is already sorted!
 Otherwise:
1. Divide the unsorted list into two sub-lists of about half
the size
 So if your list has n elements, you will divide that list into two
sub-lists, each having approximately n/2 elements:
2. Recursively sort each sub-list by calling recursively
calling Merge Sort on the two smaller lists
3. Merge the two sub-lists back into one sorted list
Sorting: Merge Sort page 21
© Dr. Jonathan (Yahya) Cazalas
Sorting: Merge Sort
 Merge Sort
 Basically, given a list:
 You will split this list into two lists of about half the size
 Then you recursively call Merge Sort on each list
 What does that do?
 Each of these new lists will, individually, be split into two lists
of about half the size.
 So now we have four lists, each about ¼ the size of the
original list
 This keeps happening…the lists keep getting split into
smaller and smaller lists
 Until you get to a list of size 1 or size 0
 Then we Merge them into a larger, sorted list
Sorting: Merge Sort page 22
© Dr. Jonathan (Yahya) Cazalas
 Merge sort idea:
 Divide the array into two halves.
 Recursively sort the two halves (using merge sort).
 Use Merge to combine the two arrays.
sort sort
merge(0, n/2, n-1)
mergeSort(0, n/2-1) mergeSort(n/2, n-1)
Sorting: Merge Sort
Sorting: Merge Sort page 23
© Dr. Jonathan (Yahya) Cazalas
67
45
23 14 6 33
98 42
Sorting: Merge Sort page 24
© Dr. Jonathan (Yahya) Cazalas
67
45
23 14 6 33
98 42
67
45
23 14 6 33
98 42
Sorting: Merge Sort page 25
© Dr. Jonathan (Yahya) Cazalas
67
45
23 14 6 33
98 42
67
45
23 14 6 33
98 42
45
23 14
98
Sorting: Merge Sort page 26
© Dr. Jonathan (Yahya) Cazalas
67
45
23 14 6 33
98 42
67
45
23 14 6 33
98 42
45
23 14
98
23
98
Sorting: Merge Sort page 27
© Dr. Jonathan (Yahya) Cazalas
67
45
23 14 6 33
98 42
67
45
23 14 6 33
98 42
45
23 14
98
23
98
Merge
Sorting: Merge Sort page 28
© Dr. Jonathan (Yahya) Cazalas
67
45
23 14 6 33
98 42
67
45
23 14 6 33
98 42
45
23 14
98
23
98
23
Merge
Sorting: Merge Sort page 29
© Dr. Jonathan (Yahya) Cazalas
67
45
23 14 6 33
98 42
67
45
23 14 6 33
98 42
45
23 14
98
23
98
23 98
Merge
Sorting: Merge Sort page 30
© Dr. Jonathan (Yahya) Cazalas
67
45
23 14 6 33
98 42
67
45
23 14 6 33
98 42
45
23 14
98
23
98 45 14
23 98
Sorting: Merge Sort page 31
© Dr. Jonathan (Yahya) Cazalas
67
45
23 14 6 33
98 42
67
45
23 14 6 33
98 42
45
23 14
98
23
98 45 14
Merge
23 98
Sorting: Merge Sort page 32
© Dr. Jonathan (Yahya) Cazalas
67
45
23 14 6 33
98 42
67
45
23 14 6 33
98 42
45
23 14
98
23
98 45 14
14
Merge
23 98
Sorting: Merge Sort page 33
© Dr. Jonathan (Yahya) Cazalas
67
45
23 14 6 33
98 42
67
45
23 14 6 33
98 42
45
23 14
98
23
98 45 14
45
Merge
23 98 14
Sorting: Merge Sort page 34
© Dr. Jonathan (Yahya) Cazalas
67
45
23 14 6 33
98 42
67
45
23 14 6 33
98 42
45
23 14
98
23
98 45 14
Merge
98 45
14
23
Sorting: Merge Sort page 35
© Dr. Jonathan (Yahya) Cazalas
67
45
23 14 6 33
98 42
67
45
23 14 6 33
98 42
45
23 14
98
23
98 45 14
Merge
98 14
14
23 45
Sorting: Merge Sort page 36
© Dr. Jonathan (Yahya) Cazalas
67
45
23 14 6 33
98 42
67
45
23 14 6 33
98 42
45
23 14
98
23
98 45 14
Merge
23 14
14 23
98 45
Sorting: Merge Sort page 37
© Dr. Jonathan (Yahya) Cazalas
67
45
23 14 6 33
98 42
67
45
23 14 6 33
98 42
45
23 14
98
23
98 45 14
Merge
23 98 45
14
14 23 45
Sorting: Merge Sort page 38
© Dr. Jonathan (Yahya) Cazalas
67
45
23 14 6 33
98 42
67
45
23 14 6 33
98 42
45
23 14
98
23
98 45 14
Merge
23 98 45
14
14 23 45 98
Sorting: Merge Sort page 39
© Dr. Jonathan (Yahya) Cazalas
67
45
23 14 6 33
98 42
67
45
23 14 6 33
98 42
45
23 14
98
23
98 45 14
67
6 33 42
23 98 45
14
14 23 45 98
Sorting: Merge Sort page 40
© Dr. Jonathan (Yahya) Cazalas
67
45
23 14 6 33
98 42
67
45
23 14 6 33
98 42
45
23 14
98
23
98 45 14
67
6 33 42
67
6
23 98 45
14
14 23 45 98
Sorting: Merge Sort page 41
© Dr. Jonathan (Yahya) Cazalas
67
45
23 14 6 33
98 42
67
45
23 14 6 33
98 42
45
23 14
98
23
98 45 14
67
6 33 42
67
6
Merge
23 98 45
14
14 23 45 98
Sorting: Merge Sort page 42
© Dr. Jonathan (Yahya) Cazalas
67
45
23 14 6 33
98 42
67
45
23 14 6 33
98 42
45
23 14
98
23
98 45 14
67
6 33 42
67
6
6
Merge
23 98 45
14
14 23 45 98
Sorting: Merge Sort page 43
© Dr. Jonathan (Yahya) Cazalas
67
45
23 14 6 33
98 42
67
45
23 14 6 33
98 42
45
23 14
98
23
98 45 14
67
6 33 42
67
6
67
Merge
23 98 45
14 6
14 23 45 98
Sorting: Merge Sort page 44
© Dr. Jonathan (Yahya) Cazalas
67
45
23 14 6 33
98 42
67
45
23 14 6 33
98 42
45
23 14
98
23
98 45 14
67
6 33 42
67
6 33 42
23 98 45
14 67
6
14 23 45 98
Sorting: Merge Sort page 45
© Dr. Jonathan (Yahya) Cazalas
67
45
23 14 6 33
98 42
67
45
23 14 6 33
98 42
45
23 14
98
23
98 45 14
67
6 33 42
67
6 33 42
Merge
23 98 45
14 67
6
14 23 45 98
Sorting: Merge Sort page 46
© Dr. Jonathan (Yahya) Cazalas
67
45
23 14 6 33
98 42
67
45
23 14 6 33
98 42
45
23 14
98
23
98 45 14
67
6 33 42
67
6 33 42
Merge
33
23 98 45
14 67
6
14 23 45 98
Sorting: Merge Sort page 47
© Dr. Jonathan (Yahya) Cazalas
67
45
23 14 6 33
98 42
67
45
23 14 6 33
98 42
45
23 14
98
23
98 45 14
67
6 33 42
67
6 33 42
Merge
42
23 98 45
14 67
6 33
14 23 45 98
Sorting: Merge Sort page 48
© Dr. Jonathan (Yahya) Cazalas
67
45
23 14 6 33
98 42
67
45
23 14 6 33
98 42
45
23 14
98
23
98 45 14
67
6 33 42
67
6 33 42
Merge
23 98 45
14 67
6 42
33
14 23 45 98
Sorting: Merge Sort page 49
© Dr. Jonathan (Yahya) Cazalas
67
45
23 14 6 33
98 42
67
45
23 14 6 33
98 42
45
23 14
98
23
98 45 14
67
6 33 42
67
6 33 42
Merge
23 98 45
14 6 42
33
14 23 45 98 6
67
Sorting: Merge Sort page 50
© Dr. Jonathan (Yahya) Cazalas
67
45
23 14 6 33
98 42
67
45
23 14 6 33
98 42
45
23 14
98
23
98 45 14
67
6 33 42
67
6 33 42
Merge
23 98 45
14 6 33
14 23 45 98 6 33
67 42
Sorting: Merge Sort page 51
© Dr. Jonathan (Yahya) Cazalas
67
45
23 14 6 33
98 42
67
45
23 14 6 33
98 42
45
23 14
98
23
98 45 14
67
6 33 42
67
6 33 42
Merge
23 98 45
14 6 42
33
14 23 45 98 6 33 42
67
Sorting: Merge Sort page 52
© Dr. Jonathan (Yahya) Cazalas
67
45
23 14 6 33
98 42
67
45
23 14 6 33
98 42
45
23 14
98
23
98 45 14
67
6 33 42
67
6 33 42
Merge
23 98 45
14 67
6 42
33
14 23 45 98 6 33 42 67
Sorting: Merge Sort page 53
© Dr. Jonathan (Yahya) Cazalas
67
45
23 14 6 33
98 42
67
45
23 14 6 33
98 42
45
23 14
98
23
98 45 14
67
6 33 42
67
6 33 42
Merge
23 98 45
14 67
6 42
33
23 45 98 33 42 67
14 6
Sorting: Merge Sort page 54
© Dr. Jonathan (Yahya) Cazalas
67
45
23 14 6 33
98 42
67
45
23 14 6 33
98 42
45
23 14
98
23
98 45 14
67
6 33 42
67
6 33 42
Merge
23 98 45
14 67
6 42
33
23 45 98 6 42 67
6
14 33
Sorting: Merge Sort page 55
© Dr. Jonathan (Yahya) Cazalas
67
45
23 14 6 33
98 42
67
45
23 14 6 33
98 42
45
23 14
98
23
98 45 14
67
6 33 42
67
6 33 42
Merge
23 98 45
14 67
6 42
33
14 45 98 6 42 67
6 14
23 33
Sorting: Merge Sort page 56
© Dr. Jonathan (Yahya) Cazalas
67
45
23 14 6 33
98 42
67
45
23 14 6 33
98 42
45
23 14
98
23
98 45 14
67
6 33 42
67
6 33 42
Merge
23 98 45
14 67
6 42
33
14 23 98 6 42 67
6 14 23
45 33
Sorting: Merge Sort page 57
© Dr. Jonathan (Yahya) Cazalas
67
45
23 14 6 33
98 42
67
45
23 14 6 33
98 42
45
23 14
98
23
98 45 14
67
6 33 42
67
6 33 42
Merge
23 98 45
14 67
6 42
33
14 23 98 6 33 67
6 14 23 33
45 42
Sorting: Merge Sort page 58
© Dr. Jonathan (Yahya) Cazalas
67
45
23 14 6 33
98 42
67
45
23 14 6 33
98 42
45
23 14
98
23
98 45 14
67
6 33 42
67
6 33 42
Merge
23 98 45
14 67
6 42
33
14 23 98 6 33 42
6 14 23 33 42
45 67
Sorting: Merge Sort page 59
© Dr. Jonathan (Yahya) Cazalas
67
45
23 14 6 33
98 42
67
45
23 14 6 33
98 42
45
23 14
98
23
98 45 14
67
6 33 42
67
6 33 42
Merge
23 98 45
14 67
6 42
33
14 23 45 6 33 42
6 14 23 33 42 45
98 67
Sorting: Merge Sort page 60
© Dr. Jonathan (Yahya) Cazalas
67
45
23 14 6 33
98 42
67
45
23 14 6 33
98 42
45
23 14
98
23
98 45 14
67
6 33 42
67
6 33 42
Merge
23 98 45
14 67
6 42
33
14 23 45 98 6 33 42 67
6 14 23 33 42 45 67
Sorting: Merge Sort page 61
© Dr. Jonathan (Yahya) Cazalas
67
45
23 14 6 33
98 42
67
45
23 14 6 33
98 42
45
23 14
98
23
98 45 14
67
6 33 42
67
6 33 42
Merge
23 98 45
14 67
6 42
33
14 23 45 98 6 33 42 67
6 14 23 33 42 45 67 98
Sorting: Merge Sort page 62
© Dr. Jonathan (Yahya) Cazalas
67
45
23 14 6 33
98 42
67
45
23 14 6 33
98 42
45
23 14
98
23
98 45 14
67
6 33 42
67
6 33 42
23 98 45
14 67
6 42
33
14 23 45 98 6 33 42 67
6 14 23 33 42 45 67 98
Sorting: Merge Sort page 63
© Dr. Jonathan (Yahya) Cazalas
67
45
23 14 6 33
98 42
6 14 23 33 42 45 67 98
Sorting: Merge Sort page 64
© Dr. Jonathan (Yahya) Cazalas
Sorting: Merge Sort
 Merge Sort – Conceptual Understanding
 To make the explanation easy, we said that the
first step is to divide the array into two smaller
arrays of about equal size
 Then we recursively call Merge Sort on the first
half of the array
 Then we recursively call Merge Sort on the
second half of the array.
 Finally, we Merge.
 However, this is not what happens in code!
Sorting: Merge Sort page 65
© Dr. Jonathan (Yahya) Cazalas
Sorting: Merge Sort
 Merge Sort – Reality of the Code
 However, in reality, we do NOT divide the array
into two new arrays.
 This is unnecessary and would take a lot of memory
 What really happens?
 There is only ONE array.
 There are three steps:
1. Recursively Merge Sort the left half of the array.
2. Recursively Merge Sort the right half of the array.
3. Merge the two sorted halves together.
Sorting: Merge Sort page 66
© Dr. Jonathan (Yahya) Cazalas
Sorting: Merge Sort
 Merge Sort – Psuedocode
 Here’s the idea of what happens in the code:
method MergeSort(array) {
1. MergeSort(left half of array)
2. MergeSort(right half of Array)
3. Merge
}
Sorting: Merge Sort page 67
© Dr. Jonathan (Yahya) Cazalas
13 6 21 18 9 4 8 20
0 7
4 6 8 9 13 18 20 21
0 7
13 6 21 18
0 3
9 4 8 20
4 7
6 13 18 21
0 3
4 8 9 20
4 7
13 6
0 1
21 18
2 3
9 4
4 5
8 20
6 7
6 13
0 1
18 21
2 3
4 9
4 5
8 20
6 7
13
0
6
1
21
2
18
3
9
4
4
5
8
6
20
7
Sorting: Merge Sort (real example)
Sorting: Merge Sort page 68
© Dr. Jonathan (Yahya) Cazalas
Brief Interlude: FAIL Picture
Sorting: Merge Sort page 69
© Dr. Jonathan (Yahya) Cazalas
Daily Bike Fail
Sorting: Merge Sort page 70
© Dr. Jonathan (Yahya) Cazalas
Weekly Bike Fail
Sorting: Merge Sort page 71
© Dr. Jonathan (Yahya) Cazalas
Sorting: Merge Sort
 Merge Sort Code
public void MergeSort(int values[], int start, int end) {
int mid;
// Check if our sorting range is more than one element.
if (start < end) {
mid = (start+end)/2;
// Sort the first half of the values.
MergeSort(values, start, mid);
// Sort the last half of the values.
MergeSort(values, mid+1, end);
// Put it all together.
Merge(values, start, mid+1, end);
}
}
Sorting: Merge Sort page 72
© Dr. Jonathan (Yahya) Cazalas
Sorting: Merge Sort
 Merge Code
 This code is longer
 And a bit convoluted
 But all it does it Merge the values from two arrays into
one larger array
 Of course, keeping the items in order
 Just like the example shown earlier in the slides
 You can find Merge code in the book and online
 Or you can code it up yourself from the example shown
earlier in the slides
Sorting: Merge Sort page 73
© Dr. Jonathan (Yahya) Cazalas
Sorting: Merge Sort
 Merge Sort Analysis
 Again, here are the steps of Merge Sort:
1) Merge Sort the first half of the list
2) Merge Sort the second half of the list
3) Merge both halves together
 Let T(n) be the running time of Merge Sort on an
input size n
 Then we have:
 T(n) = (Time in step 1) + (Time in step 2) + (Time in step 3)
Sorting: Merge Sort page 74
© Dr. Jonathan (Yahya) Cazalas
Sorting: Merge Sort
 Merge Sort Analysis
 T(n): running time of Merge Sort on input size n
 Therefore, we have:
 T(n) = (Time in step 1) + (Time in step 2) + (Time in step 3)
 Notice that Step 1 and Step 2 are sorting
problems also
 But they are of size n/2
 And the Merge function runs in O(n) time
 Thus, we get the following equation for T(n)
 T(n) = T(n/2) + T(n/2) + O(n)
 T(n) = 2T(n/2) + O(n)
…we are halving the input
Sorting: Merge Sort page 75
© Dr. Jonathan (Yahya) Cazalas
Sorting: Merge Sort
 Merge Sort Analysis
 T(n) = 2T(n/2) + O(n)
 For the time being, let’s simplify O(n) to just n
 T(n) = 2T(n/2) + n
 and we know that T(1) = 1
 So we now have a Recurrence Relation
 Is it solved?
 NO!
 Why?
 Damn T’s!
Sorting: Merge Sort page 76
© Dr. Jonathan (Yahya) Cazalas
Sorting: Merge Sort
 Merge Sort Analysis
 T(n) = 2T(n/2) + n and T(1) = 1
 So we need to solve this, by removing the T(…)’s
from the right hand side
 Then T(n) will be in its closed form
 And we can state its Big-O running time
 We do this in steps
 We replace n with n/2 on both sides of the equation
 We plug the result back in
 And then we do it again…till a “light goes off” and we
see something
Sorting: Merge Sort page 77
© Dr. Jonathan (Yahya) Cazalas
Sorting: Merge Sort
 Merge Sort Analysis
 T(n) = 2T(n/2) + n
 Do you know what T(n/2) equals
 Does it equal 2,125 operations? We don’t know!
 So we need to develop an equation for T(n/2)
 How?
 Take the original equation shown above
 Wherever you see an ‘n’, substitute with ‘n/2’
 T(n/2) = 2T(n/4) + n/2
 So now we have an equation for T(n/2)
and T(1) = 1
Sorting: Merge Sort page 78
© Dr. Jonathan (Yahya) Cazalas
Sorting: Merge Sort
 Merge Sort Analysis
 T(n) = 2T(n/2) + n
 T(n/2) = 2T(n/4) + n/2
 So now we have an equation for T(n/2)
 We can take this equation and substitute it back into the
original equation
 T(n) = 2T(n/2) + n = 2[2T(n/4) + n/2] + n
 now simplify
 T(n) = 4T(n/4) + 2n
 Same thing here: do you know what T(n/4) equals?
 No we don’t! So we need to develop an eqn for T(n/4)
and T(1) = 1
Sorting: Merge Sort page 79
© Dr. Jonathan (Yahya) Cazalas
Sorting: Merge Sort
 Merge Sort Analysis
 T(n) = 2T(n/2) + n
 T(n/2) = 2T(n/4) + n/2
 T(n) = 4T(n/4) + 2n
 Same thing here: do you know what T(n/4) equals?
 No we don’t! So we need to develop an eqn for T(n/4)
 Take the eqn above and again substitute ‘n/2’ for ‘n’
 T(n/4) = 2T(n/8) + n/4
 So now we have an equation for T(n/4)
 We can take this equation and substitute it back the
equation that we currently have in terms of T(n/4)
and T(1) = 1
Sorting: Merge Sort page 80
© Dr. Jonathan (Yahya) Cazalas
Sorting: Merge Sort
 Merge Sort Analysis
 T(n) = 2T(n/2) + n
 T(n/2) = 2T(n/4) + n/2
 T(n) = 4T(n/4) + 2n
 T(n/4) = 2T(n/8) + n/4
 So now we have an equation for T(n/4)
 We can take this equation and substitute it back the
equation that we currently have in terms of T(n/4)
 T(n) = 4T(n/4) + 2n = 4[2T(n/8) + n/4] + 2n
 Simplify a bit
 T(n) = 8T(n/8) + 3n
and T(1) = 1
Sorting: Merge Sort page 81
© Dr. Jonathan (Yahya) Cazalas
Sorting: Merge Sort
 Merge Sort Analysis
 So now we have three equations for T(n):
 T(n) = 2T(n/2) + n
 T(n) = 4T(n/4) + 2n
 T(n) = 8T(n/8) + 3n
 So on the kth step/stage of the recursion, we get
a generalized recurrence relation:
 T(n) = 2kT(n/2k) +kn
 Whew! So now we’re done right?
 1st step of recursion
 2nd step of recursion
 3rd step of recursion
 kth step of recursion
Wrong!
Sorting: Merge Sort page 82
© Dr. Jonathan (Yahya) Cazalas
Sorting: Merge Sort
 Merge Sort Analysis
 So on the kth step/stage of the recursion, we get
a generalized recurrence relation:
 T(n) = 2kT(n/2k) +kn
 We need to get rid of the T(…)’s on the right side
 Remember, we know T(1) = 1
 So we make a substitution:
 Let n = 2k
 and also solve for k
 k = log2n
 Plug these back in…
Sorting: Merge Sort page 83
© Dr. Jonathan (Yahya) Cazalas
Sorting: Merge Sort
 Merge Sort Analysis
 So on the kth step/stage of the recursion, we get
a generalized recurrence relation:
 T(n) = 2kT(n/2k) +kn
 Let n = 2k
 and also solve for k
 k = log2n
 Plug these back in…
 T(n) = 2log2nT(n/n) +(log2n)n
 T(n) = n*T(1) + nlogn = n + n*logn
 So Merge Sort runs in O(n*logn) time
Sorting: Merge Sort page 84
© Dr. Jonathan (Yahya) Cazalas
Sorting: Merge Sort
 Merge Sort Summary
 Avoids all the unnecessary swaps of n2 sorts
 Uses recursion to split up a list until we get to
“lists” of 1 or 0 elements
 Uses a Merge function to merge (“sort”) these
smaller lists into larger lists
 Is MUCH faster than n2 sorts
 Merge Sort runs in O(nlogn) time
Sorting: Merge Sort page 85
© Dr. Jonathan (Yahya) Cazalas
Sorting: Merge Sort
WASN’T
THAT
THE COOLEST!
Sorting: Merge Sort page 86
© Dr. Jonathan (Yahya) Cazalas
Daily Demotivator
College of Computing & Information Technology
King Abdulaziz University
CPCS-204 – Data Structures I
Sorting:
Merge Sort

More Related Content

What's hot

Data Structures and Algorithms
Data Structures and AlgorithmsData Structures and Algorithms
Data Structures and Algorithms
Mark Jade Barrientos
 
Sorting and Its Types
Sorting and Its TypesSorting and Its Types
Sorting and Its Types
amberkhan59
 
Searching linear &amp; binary search
Searching linear &amp; binary searchSearching linear &amp; binary search
Searching linear &amp; binary search
nikunjandy
 
Java presentation on insertion sort
Java presentation on insertion sortJava presentation on insertion sort
Java presentation on insertion sort
_fahad_shaikh
 
sorting and its types
sorting and its typessorting and its types
sorting and its types
SIVASHANKARIRAJAN
 
Matrix
MatrixMatrix
Matrix
Deepak Kumar
 
Selection sorting
Selection sortingSelection sorting
Selection sorting
Himanshu Kesharwani
 
Sorting
SortingSorting
Selection sort
Selection sortSelection sort
Selection sort
amna izzat
 
Rahat &amp; juhith
Rahat &amp; juhithRahat &amp; juhith
Rahat &amp; juhith
Rj Juhith
 
Selection and insertion sort
Selection and insertion sortSelection and insertion sort
Selection and insertion sort
Ann Tugade
 
Selection and insertion sort
Selection and insertion sortSelection and insertion sort
Selection and insertion sort
Ann Tugade
 
Selection sort
Selection sortSelection sort
Selection sort
asra khan
 
Logarithms and logarithmic functions
Logarithms and logarithmic functionsLogarithms and logarithmic functions
Logarithms and logarithmic functions
Jessica Garcia
 
Unit v data structure-converted
Unit  v data structure-convertedUnit  v data structure-converted
Unit v data structure-converted
Shri Shankaracharya College, Bhilai,Junwani
 
Presentation on the topic selection sort
Presentation on the topic selection sortPresentation on the topic selection sort
Presentation on the topic selection sort
District Administration
 
Sorting and searching arrays binary search algorithm
Sorting and searching arrays binary search algorithmSorting and searching arrays binary search algorithm
Sorting and searching arrays binary search algorithm
David Burks-Courses
 
Logarithmic Functions
Logarithmic FunctionsLogarithmic Functions
Logarithmic Functions
swartzje
 
7.6 solving logarithmic equations
7.6 solving logarithmic equations7.6 solving logarithmic equations
7.6 solving logarithmic equations
swartzje
 
3rd Test - Slope and parallel lines
3rd Test - Slope and parallel lines3rd Test - Slope and parallel lines
3rd Test - Slope and parallel lines
Brandeis High School
 

What's hot (20)

Data Structures and Algorithms
Data Structures and AlgorithmsData Structures and Algorithms
Data Structures and Algorithms
 
Sorting and Its Types
Sorting and Its TypesSorting and Its Types
Sorting and Its Types
 
Searching linear &amp; binary search
Searching linear &amp; binary searchSearching linear &amp; binary search
Searching linear &amp; binary search
 
Java presentation on insertion sort
Java presentation on insertion sortJava presentation on insertion sort
Java presentation on insertion sort
 
sorting and its types
sorting and its typessorting and its types
sorting and its types
 
Matrix
MatrixMatrix
Matrix
 
Selection sorting
Selection sortingSelection sorting
Selection sorting
 
Sorting
SortingSorting
Sorting
 
Selection sort
Selection sortSelection sort
Selection sort
 
Rahat &amp; juhith
Rahat &amp; juhithRahat &amp; juhith
Rahat &amp; juhith
 
Selection and insertion sort
Selection and insertion sortSelection and insertion sort
Selection and insertion sort
 
Selection and insertion sort
Selection and insertion sortSelection and insertion sort
Selection and insertion sort
 
Selection sort
Selection sortSelection sort
Selection sort
 
Logarithms and logarithmic functions
Logarithms and logarithmic functionsLogarithms and logarithmic functions
Logarithms and logarithmic functions
 
Unit v data structure-converted
Unit  v data structure-convertedUnit  v data structure-converted
Unit v data structure-converted
 
Presentation on the topic selection sort
Presentation on the topic selection sortPresentation on the topic selection sort
Presentation on the topic selection sort
 
Sorting and searching arrays binary search algorithm
Sorting and searching arrays binary search algorithmSorting and searching arrays binary search algorithm
Sorting and searching arrays binary search algorithm
 
Logarithmic Functions
Logarithmic FunctionsLogarithmic Functions
Logarithmic Functions
 
7.6 solving logarithmic equations
7.6 solving logarithmic equations7.6 solving logarithmic equations
7.6 solving logarithmic equations
 
3rd Test - Slope and parallel lines
3rd Test - Slope and parallel lines3rd Test - Slope and parallel lines
3rd Test - Slope and parallel lines
 

Similar to merge_sort

quick_sort
quick_sortquick_sort
quick_sort
Mohamed Elsayed
 
College algebra p2
College algebra p2College algebra p2
College algebra p2
Jeneva Clark
 
Quick Sort in data structure.pptx
Quick Sort in data structure.pptxQuick Sort in data structure.pptx
Quick Sort in data structure.pptx
ujjwalmatoliya
 
Sienna6bst 120411102353-phpapp02
Sienna6bst 120411102353-phpapp02Sienna6bst 120411102353-phpapp02
Sienna6bst 120411102353-phpapp02
Getachew Ganfur
 
Sorting-algorithmbhddcbjkmbgjkuygbjkkius.pdf
Sorting-algorithmbhddcbjkmbgjkuygbjkkius.pdfSorting-algorithmbhddcbjkmbgjkuygbjkkius.pdf
Sorting-algorithmbhddcbjkmbgjkuygbjkkius.pdf
ArjunSingh81957
 
heaps2
heaps2heaps2
Algo PPT.pdf
Algo PPT.pdfAlgo PPT.pdf
Algo PPT.pdf
sheraz7288
 
Sorting types and Algorithms
Sorting types and AlgorithmsSorting types and Algorithms
Sorting types and Algorithms
Ali Khan
 
RDBMS concepts
RDBMS conceptsRDBMS concepts
Tableau groups vs sets
Tableau groups vs setsTableau groups vs sets
Tableau groups vs sets
Vizual Intelligence Consulting
 
recursion3
recursion3recursion3
recursion3
Mohamed Elsayed
 
Merge sort
Merge sortMerge sort
Merge sort
kajalsharma161
 
Weka Term Paper_VGSoM_10BM60011
Weka Term Paper_VGSoM_10BM60011Weka Term Paper_VGSoM_10BM60011
Weka Term Paper_VGSoM_10BM60011
Amu Singh
 
10 merge sort
10 merge sort10 merge sort
10 merge sort
irdginfo
 

Similar to merge_sort (14)

quick_sort
quick_sortquick_sort
quick_sort
 
College algebra p2
College algebra p2College algebra p2
College algebra p2
 
Quick Sort in data structure.pptx
Quick Sort in data structure.pptxQuick Sort in data structure.pptx
Quick Sort in data structure.pptx
 
Sienna6bst 120411102353-phpapp02
Sienna6bst 120411102353-phpapp02Sienna6bst 120411102353-phpapp02
Sienna6bst 120411102353-phpapp02
 
Sorting-algorithmbhddcbjkmbgjkuygbjkkius.pdf
Sorting-algorithmbhddcbjkmbgjkuygbjkkius.pdfSorting-algorithmbhddcbjkmbgjkuygbjkkius.pdf
Sorting-algorithmbhddcbjkmbgjkuygbjkkius.pdf
 
heaps2
heaps2heaps2
heaps2
 
Algo PPT.pdf
Algo PPT.pdfAlgo PPT.pdf
Algo PPT.pdf
 
Sorting types and Algorithms
Sorting types and AlgorithmsSorting types and Algorithms
Sorting types and Algorithms
 
RDBMS concepts
RDBMS conceptsRDBMS concepts
RDBMS concepts
 
Tableau groups vs sets
Tableau groups vs setsTableau groups vs sets
Tableau groups vs sets
 
recursion3
recursion3recursion3
recursion3
 
Merge sort
Merge sortMerge sort
Merge sort
 
Weka Term Paper_VGSoM_10BM60011
Weka Term Paper_VGSoM_10BM60011Weka Term Paper_VGSoM_10BM60011
Weka Term Paper_VGSoM_10BM60011
 
10 merge sort
10 merge sort10 merge sort
10 merge sort
 

More from Mohamed Elsayed

binary_trees4
binary_trees4binary_trees4
binary_trees4
Mohamed Elsayed
 
binary_trees3
binary_trees3binary_trees3
binary_trees3
Mohamed Elsayed
 
binary_trees2
binary_trees2binary_trees2
binary_trees2
Mohamed Elsayed
 
binary_trees1
binary_trees1binary_trees1
binary_trees1
Mohamed Elsayed
 
queues
queuesqueues
stacks2
stacks2stacks2
stacks1
stacks1stacks1
algorithm_analysis2
algorithm_analysis2algorithm_analysis2
algorithm_analysis2
Mohamed Elsayed
 
algorithm_analysis1
algorithm_analysis1algorithm_analysis1
algorithm_analysis1
Mohamed Elsayed
 
recursion2
recursion2recursion2
recursion2
Mohamed Elsayed
 
recursion1
recursion1recursion1
recursion1
Mohamed Elsayed
 
linked_lists4
linked_lists4linked_lists4
linked_lists4
Mohamed Elsayed
 
linked_lists3
linked_lists3linked_lists3
linked_lists3
Mohamed Elsayed
 
Linked_lists2
Linked_lists2Linked_lists2
Linked_lists2
Mohamed Elsayed
 
linked_lists
linked_listslinked_lists
linked_lists
Mohamed Elsayed
 
binary_search
binary_searchbinary_search
binary_search
Mohamed Elsayed
 
arrays
arraysarrays
introduction
introductionintroduction
introduction
Mohamed Elsayed
 
heaps
heapsheaps
hash_tables
hash_tableshash_tables
hash_tables
Mohamed Elsayed
 

More from Mohamed Elsayed (20)

binary_trees4
binary_trees4binary_trees4
binary_trees4
 
binary_trees3
binary_trees3binary_trees3
binary_trees3
 
binary_trees2
binary_trees2binary_trees2
binary_trees2
 
binary_trees1
binary_trees1binary_trees1
binary_trees1
 
queues
queuesqueues
queues
 
stacks2
stacks2stacks2
stacks2
 
stacks1
stacks1stacks1
stacks1
 
algorithm_analysis2
algorithm_analysis2algorithm_analysis2
algorithm_analysis2
 
algorithm_analysis1
algorithm_analysis1algorithm_analysis1
algorithm_analysis1
 
recursion2
recursion2recursion2
recursion2
 
recursion1
recursion1recursion1
recursion1
 
linked_lists4
linked_lists4linked_lists4
linked_lists4
 
linked_lists3
linked_lists3linked_lists3
linked_lists3
 
Linked_lists2
Linked_lists2Linked_lists2
Linked_lists2
 
linked_lists
linked_listslinked_lists
linked_lists
 
binary_search
binary_searchbinary_search
binary_search
 
arrays
arraysarrays
arrays
 
introduction
introductionintroduction
introduction
 
heaps
heapsheaps
heaps
 
hash_tables
hash_tableshash_tables
hash_tables
 

Recently uploaded

PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
AyyanKhan40
 
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
imrankhan141184
 
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
Nguyen Thanh Tu Collection
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Excellence Foundation for South Sudan
 
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptxPrésentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
siemaillard
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
Dr. Shivangi Singh Parihar
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Fajar Baskoro
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
RAHUL
 
Chapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptxChapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptx
Denish Jangid
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
Nicholas Montgomery
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
Israel Genealogy Research Association
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
Nguyen Thanh Tu Collection
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
TechSoup
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
mulvey2
 
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptxNEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
iammrhaywood
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
eBook.com.bd (প্রয়োজনীয় বাংলা বই)
 
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
สมใจ จันสุกสี
 
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skillsspot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
haiqairshad
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
Dr. Mulla Adam Ali
 
How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience
Wahiba Chair Training & Consulting
 

Recently uploaded (20)

PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
 
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
 
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
 
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptxPrésentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
 
Chapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptxChapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptx
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
 
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptxNEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
 
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
 
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skillsspot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
 
How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience
 

merge_sort

  • 1. College of Computing & Information Technology King Abdulaziz University CPCS-204 – Data Structures I Sorting: Merge Sort
  • 2. Sorting: Merge Sort page 2 © Dr. Jonathan (Yahya) Cazalas Sorting: Merge Sort  Problem with Bubble/Insertion/Selection Sorts:  All of these sorts make a large number of comparisons and swaps between elements  As mentioned last class (while covering n2 sorts):  Any algorithm that swaps adjacent elements can only run so fast  So one might ask is there a more clever way to sort numbers  A way that does not require looking at all these pairs  Indeed, there are several ways to do this  And one of them is Merge Sort
  • 3. Sorting: Merge Sort page 3 © Dr. Jonathan (Yahya) Cazalas Sorting: Merge Sort  Merge Sort  Conceptually, Merge Sort works as follows:  If the “list” is of length 0 or 1, then it is already sorted!  Otherwise: 1. Divide the unsorted list into two sub-lists of about half the size  So if your list has n elements, you will divide that list into two sub-lists, each having approximately n/2 elements: 2. Recursively sort each sub-list by calling recursively calling Merge Sort on the two smaller lists 3. Merge the two sub-lists back into one sorted list  This Merge is a function that we study on its own  In a bit…
  • 4. Sorting: Merge Sort page 4 © Dr. Jonathan (Yahya) Cazalas Sorting: Merge Sort  Merge Sort  Basically, given a list:  You will split this list into two lists of about half the size  Then you recursively call Merge Sort on each list  What does that do?  Each of these new lists will, individually, be split into two lists of about half the size.  So now we have four lists, each about ¼ the size of the original list  This keeps happening…the lists keep getting split into smaller and smaller lists  Until you get to a list of size 1 or size 0  Then we Merge them into a larger, sorted list …which is sorted!
  • 5. Sorting: Merge Sort page 5 © Dr. Jonathan (Yahya) Cazalas Sorting: Merge Sort  Merge Sort  Incorporates two main ideas to improve its runtime: 1) A small list will take fewer steps to sort than a large list 2) Fewer steps are required to construct a sorted list from two sorted lists than two unsorted lists  For example:  You only have to traverse each list once if they’re already sorted
  • 6. Sorting: Merge Sort page 6 © Dr. Jonathan (Yahya) Cazalas Sorting: Merge Sort  Merge function  The key to Merge Sort: the Merge function  Given two sorted lists, Merge them into one sorted list  Problem:  You are given two arrays, each of which is already sorted  Your job is to efficiently combine the two arrays into one larger array  The larger array should contain all the values of the two smaller arrays  Finally, the larger array should be in sorted order
  • 7. Sorting: Merge Sort page 7 © Dr. Jonathan (Yahya) Cazalas Sorting: Merge Sort  Merge function  The key to Merge Sort: the Merge function  Given two sorted lists, Merge them into one sorted list  If you have two lists:  X (x1<x2<…<xm) and Y (y1<y2<…<yn)  Merge these into one list: Z (z1<z2<…<zm+n)  Example:  List 1 = {3, 8, 9} and List 2 = {1, 5, 7}  Merge(List 1, List 2) = {1, 3, 5, 7, 8, 9}
  • 8. Sorting: Merge Sort page 8 © Dr. Jonathan (Yahya) Cazalas Sorting: Merge Sort  Merge function  Solution:  Keep track of the smallest value in each array that hasn’t been placed, in order, in the larger array yet  Compare these two smallest values from each array  One of these MUST be the smallest of all the values in both arrays that are left  Place the smallest of the two values in the next location in the larger array  Adjust the smallest value for the appropriate array  Continue this process until all values have been placed in the large array
  • 9. Sorting: Merge Sort page 9 © Dr. Jonathan (Yahya) Cazalas 3 10 23 54 1 5 25 75 X: Y: Result:  Example of Merge function: Sorting: Merge Sort
  • 10. Sorting: Merge Sort page 10 © Dr. Jonathan (Yahya) Cazalas 3 10 23 54 5 25 75 1 X: Y: Result:  Example of Merge function: Sorting: Merge Sort
  • 11. Sorting: Merge Sort page 11 © Dr. Jonathan (Yahya) Cazalas 10 23 54 5 25 75 1 3 X: Y: Result: Sorting: Merge Sort  Example of Merge function:
  • 12. Sorting: Merge Sort page 12 © Dr. Jonathan (Yahya) Cazalas 10 23 54 25 75 1 3 5 X: Y: Result: Sorting: Merge Sort  Example of Merge function:
  • 13. Sorting: Merge Sort page 13 © Dr. Jonathan (Yahya) Cazalas 23 54 25 75 1 3 5 10 X: Y: Result: Sorting: Merge Sort  Example of Merge function:
  • 14. Sorting: Merge Sort page 14 © Dr. Jonathan (Yahya) Cazalas 54 25 75 1 3 5 10 23 X: Y: Result: Sorting: Merge Sort  Example of Merge function:
  • 15. Sorting: Merge Sort page 15 © Dr. Jonathan (Yahya) Cazalas 54 75 1 3 5 10 23 25 X: Y: Result: Sorting: Merge Sort  Example of Merge function:
  • 16. Sorting: Merge Sort page 16 © Dr. Jonathan (Yahya) Cazalas 75 1 3 5 10 23 25 54 X: Y: Result: Sorting: Merge Sort  Example of Merge function:
  • 17. Sorting: Merge Sort page 17 © Dr. Jonathan (Yahya) Cazalas 1 3 5 10 23 25 54 75 X: Y: Result: Sorting: Merge Sort  Example of Merge function:
  • 18. Sorting: Merge Sort page 18 © Dr. Jonathan (Yahya) Cazalas Sorting: Merge Sort  Merge function  The big question:  How can we use this Merge function to sort an entire, unsorted array?  This function only “sorts” a specific scenario:  You have to have two, already sorted, arrays  Merge can then “sort” (merge) them into one larger array  So can we use this Merge function to somehow sort a large, unsorted array???  This brings us back to Merge Sort
  • 19. Sorting: Merge Sort page 19 © Dr. Jonathan (Yahya) Cazalas Sorting: Merge Sort  Merge Sort  Again, here is the main idea for Merge Sort: 1) Sort the first half of the array, using Merge Sort 2) Sort the second half of the array, using Merge Sort  Now, we do indeed have a situation where we can use the Merge function!  Each half is already sorted! 3) So simply merge the first half of the array with the second half.  And this points to a recursive solution…
  • 20. Sorting: Merge Sort page 20 © Dr. Jonathan (Yahya) Cazalas Sorting: Merge Sort  Merge Sort  Conceptually, Merge Sort works as follows:  If the “list” is of length 0 or 1, then it is already sorted!  Otherwise: 1. Divide the unsorted list into two sub-lists of about half the size  So if your list has n elements, you will divide that list into two sub-lists, each having approximately n/2 elements: 2. Recursively sort each sub-list by calling recursively calling Merge Sort on the two smaller lists 3. Merge the two sub-lists back into one sorted list
  • 21. Sorting: Merge Sort page 21 © Dr. Jonathan (Yahya) Cazalas Sorting: Merge Sort  Merge Sort  Basically, given a list:  You will split this list into two lists of about half the size  Then you recursively call Merge Sort on each list  What does that do?  Each of these new lists will, individually, be split into two lists of about half the size.  So now we have four lists, each about ¼ the size of the original list  This keeps happening…the lists keep getting split into smaller and smaller lists  Until you get to a list of size 1 or size 0  Then we Merge them into a larger, sorted list
  • 22. Sorting: Merge Sort page 22 © Dr. Jonathan (Yahya) Cazalas  Merge sort idea:  Divide the array into two halves.  Recursively sort the two halves (using merge sort).  Use Merge to combine the two arrays. sort sort merge(0, n/2, n-1) mergeSort(0, n/2-1) mergeSort(n/2, n-1) Sorting: Merge Sort
  • 23. Sorting: Merge Sort page 23 © Dr. Jonathan (Yahya) Cazalas 67 45 23 14 6 33 98 42
  • 24. Sorting: Merge Sort page 24 © Dr. Jonathan (Yahya) Cazalas 67 45 23 14 6 33 98 42 67 45 23 14 6 33 98 42
  • 25. Sorting: Merge Sort page 25 © Dr. Jonathan (Yahya) Cazalas 67 45 23 14 6 33 98 42 67 45 23 14 6 33 98 42 45 23 14 98
  • 26. Sorting: Merge Sort page 26 © Dr. Jonathan (Yahya) Cazalas 67 45 23 14 6 33 98 42 67 45 23 14 6 33 98 42 45 23 14 98 23 98
  • 27. Sorting: Merge Sort page 27 © Dr. Jonathan (Yahya) Cazalas 67 45 23 14 6 33 98 42 67 45 23 14 6 33 98 42 45 23 14 98 23 98 Merge
  • 28. Sorting: Merge Sort page 28 © Dr. Jonathan (Yahya) Cazalas 67 45 23 14 6 33 98 42 67 45 23 14 6 33 98 42 45 23 14 98 23 98 23 Merge
  • 29. Sorting: Merge Sort page 29 © Dr. Jonathan (Yahya) Cazalas 67 45 23 14 6 33 98 42 67 45 23 14 6 33 98 42 45 23 14 98 23 98 23 98 Merge
  • 30. Sorting: Merge Sort page 30 © Dr. Jonathan (Yahya) Cazalas 67 45 23 14 6 33 98 42 67 45 23 14 6 33 98 42 45 23 14 98 23 98 45 14 23 98
  • 31. Sorting: Merge Sort page 31 © Dr. Jonathan (Yahya) Cazalas 67 45 23 14 6 33 98 42 67 45 23 14 6 33 98 42 45 23 14 98 23 98 45 14 Merge 23 98
  • 32. Sorting: Merge Sort page 32 © Dr. Jonathan (Yahya) Cazalas 67 45 23 14 6 33 98 42 67 45 23 14 6 33 98 42 45 23 14 98 23 98 45 14 14 Merge 23 98
  • 33. Sorting: Merge Sort page 33 © Dr. Jonathan (Yahya) Cazalas 67 45 23 14 6 33 98 42 67 45 23 14 6 33 98 42 45 23 14 98 23 98 45 14 45 Merge 23 98 14
  • 34. Sorting: Merge Sort page 34 © Dr. Jonathan (Yahya) Cazalas 67 45 23 14 6 33 98 42 67 45 23 14 6 33 98 42 45 23 14 98 23 98 45 14 Merge 98 45 14 23
  • 35. Sorting: Merge Sort page 35 © Dr. Jonathan (Yahya) Cazalas 67 45 23 14 6 33 98 42 67 45 23 14 6 33 98 42 45 23 14 98 23 98 45 14 Merge 98 14 14 23 45
  • 36. Sorting: Merge Sort page 36 © Dr. Jonathan (Yahya) Cazalas 67 45 23 14 6 33 98 42 67 45 23 14 6 33 98 42 45 23 14 98 23 98 45 14 Merge 23 14 14 23 98 45
  • 37. Sorting: Merge Sort page 37 © Dr. Jonathan (Yahya) Cazalas 67 45 23 14 6 33 98 42 67 45 23 14 6 33 98 42 45 23 14 98 23 98 45 14 Merge 23 98 45 14 14 23 45
  • 38. Sorting: Merge Sort page 38 © Dr. Jonathan (Yahya) Cazalas 67 45 23 14 6 33 98 42 67 45 23 14 6 33 98 42 45 23 14 98 23 98 45 14 Merge 23 98 45 14 14 23 45 98
  • 39. Sorting: Merge Sort page 39 © Dr. Jonathan (Yahya) Cazalas 67 45 23 14 6 33 98 42 67 45 23 14 6 33 98 42 45 23 14 98 23 98 45 14 67 6 33 42 23 98 45 14 14 23 45 98
  • 40. Sorting: Merge Sort page 40 © Dr. Jonathan (Yahya) Cazalas 67 45 23 14 6 33 98 42 67 45 23 14 6 33 98 42 45 23 14 98 23 98 45 14 67 6 33 42 67 6 23 98 45 14 14 23 45 98
  • 41. Sorting: Merge Sort page 41 © Dr. Jonathan (Yahya) Cazalas 67 45 23 14 6 33 98 42 67 45 23 14 6 33 98 42 45 23 14 98 23 98 45 14 67 6 33 42 67 6 Merge 23 98 45 14 14 23 45 98
  • 42. Sorting: Merge Sort page 42 © Dr. Jonathan (Yahya) Cazalas 67 45 23 14 6 33 98 42 67 45 23 14 6 33 98 42 45 23 14 98 23 98 45 14 67 6 33 42 67 6 6 Merge 23 98 45 14 14 23 45 98
  • 43. Sorting: Merge Sort page 43 © Dr. Jonathan (Yahya) Cazalas 67 45 23 14 6 33 98 42 67 45 23 14 6 33 98 42 45 23 14 98 23 98 45 14 67 6 33 42 67 6 67 Merge 23 98 45 14 6 14 23 45 98
  • 44. Sorting: Merge Sort page 44 © Dr. Jonathan (Yahya) Cazalas 67 45 23 14 6 33 98 42 67 45 23 14 6 33 98 42 45 23 14 98 23 98 45 14 67 6 33 42 67 6 33 42 23 98 45 14 67 6 14 23 45 98
  • 45. Sorting: Merge Sort page 45 © Dr. Jonathan (Yahya) Cazalas 67 45 23 14 6 33 98 42 67 45 23 14 6 33 98 42 45 23 14 98 23 98 45 14 67 6 33 42 67 6 33 42 Merge 23 98 45 14 67 6 14 23 45 98
  • 46. Sorting: Merge Sort page 46 © Dr. Jonathan (Yahya) Cazalas 67 45 23 14 6 33 98 42 67 45 23 14 6 33 98 42 45 23 14 98 23 98 45 14 67 6 33 42 67 6 33 42 Merge 33 23 98 45 14 67 6 14 23 45 98
  • 47. Sorting: Merge Sort page 47 © Dr. Jonathan (Yahya) Cazalas 67 45 23 14 6 33 98 42 67 45 23 14 6 33 98 42 45 23 14 98 23 98 45 14 67 6 33 42 67 6 33 42 Merge 42 23 98 45 14 67 6 33 14 23 45 98
  • 48. Sorting: Merge Sort page 48 © Dr. Jonathan (Yahya) Cazalas 67 45 23 14 6 33 98 42 67 45 23 14 6 33 98 42 45 23 14 98 23 98 45 14 67 6 33 42 67 6 33 42 Merge 23 98 45 14 67 6 42 33 14 23 45 98
  • 49. Sorting: Merge Sort page 49 © Dr. Jonathan (Yahya) Cazalas 67 45 23 14 6 33 98 42 67 45 23 14 6 33 98 42 45 23 14 98 23 98 45 14 67 6 33 42 67 6 33 42 Merge 23 98 45 14 6 42 33 14 23 45 98 6 67
  • 50. Sorting: Merge Sort page 50 © Dr. Jonathan (Yahya) Cazalas 67 45 23 14 6 33 98 42 67 45 23 14 6 33 98 42 45 23 14 98 23 98 45 14 67 6 33 42 67 6 33 42 Merge 23 98 45 14 6 33 14 23 45 98 6 33 67 42
  • 51. Sorting: Merge Sort page 51 © Dr. Jonathan (Yahya) Cazalas 67 45 23 14 6 33 98 42 67 45 23 14 6 33 98 42 45 23 14 98 23 98 45 14 67 6 33 42 67 6 33 42 Merge 23 98 45 14 6 42 33 14 23 45 98 6 33 42 67
  • 52. Sorting: Merge Sort page 52 © Dr. Jonathan (Yahya) Cazalas 67 45 23 14 6 33 98 42 67 45 23 14 6 33 98 42 45 23 14 98 23 98 45 14 67 6 33 42 67 6 33 42 Merge 23 98 45 14 67 6 42 33 14 23 45 98 6 33 42 67
  • 53. Sorting: Merge Sort page 53 © Dr. Jonathan (Yahya) Cazalas 67 45 23 14 6 33 98 42 67 45 23 14 6 33 98 42 45 23 14 98 23 98 45 14 67 6 33 42 67 6 33 42 Merge 23 98 45 14 67 6 42 33 23 45 98 33 42 67 14 6
  • 54. Sorting: Merge Sort page 54 © Dr. Jonathan (Yahya) Cazalas 67 45 23 14 6 33 98 42 67 45 23 14 6 33 98 42 45 23 14 98 23 98 45 14 67 6 33 42 67 6 33 42 Merge 23 98 45 14 67 6 42 33 23 45 98 6 42 67 6 14 33
  • 55. Sorting: Merge Sort page 55 © Dr. Jonathan (Yahya) Cazalas 67 45 23 14 6 33 98 42 67 45 23 14 6 33 98 42 45 23 14 98 23 98 45 14 67 6 33 42 67 6 33 42 Merge 23 98 45 14 67 6 42 33 14 45 98 6 42 67 6 14 23 33
  • 56. Sorting: Merge Sort page 56 © Dr. Jonathan (Yahya) Cazalas 67 45 23 14 6 33 98 42 67 45 23 14 6 33 98 42 45 23 14 98 23 98 45 14 67 6 33 42 67 6 33 42 Merge 23 98 45 14 67 6 42 33 14 23 98 6 42 67 6 14 23 45 33
  • 57. Sorting: Merge Sort page 57 © Dr. Jonathan (Yahya) Cazalas 67 45 23 14 6 33 98 42 67 45 23 14 6 33 98 42 45 23 14 98 23 98 45 14 67 6 33 42 67 6 33 42 Merge 23 98 45 14 67 6 42 33 14 23 98 6 33 67 6 14 23 33 45 42
  • 58. Sorting: Merge Sort page 58 © Dr. Jonathan (Yahya) Cazalas 67 45 23 14 6 33 98 42 67 45 23 14 6 33 98 42 45 23 14 98 23 98 45 14 67 6 33 42 67 6 33 42 Merge 23 98 45 14 67 6 42 33 14 23 98 6 33 42 6 14 23 33 42 45 67
  • 59. Sorting: Merge Sort page 59 © Dr. Jonathan (Yahya) Cazalas 67 45 23 14 6 33 98 42 67 45 23 14 6 33 98 42 45 23 14 98 23 98 45 14 67 6 33 42 67 6 33 42 Merge 23 98 45 14 67 6 42 33 14 23 45 6 33 42 6 14 23 33 42 45 98 67
  • 60. Sorting: Merge Sort page 60 © Dr. Jonathan (Yahya) Cazalas 67 45 23 14 6 33 98 42 67 45 23 14 6 33 98 42 45 23 14 98 23 98 45 14 67 6 33 42 67 6 33 42 Merge 23 98 45 14 67 6 42 33 14 23 45 98 6 33 42 67 6 14 23 33 42 45 67
  • 61. Sorting: Merge Sort page 61 © Dr. Jonathan (Yahya) Cazalas 67 45 23 14 6 33 98 42 67 45 23 14 6 33 98 42 45 23 14 98 23 98 45 14 67 6 33 42 67 6 33 42 Merge 23 98 45 14 67 6 42 33 14 23 45 98 6 33 42 67 6 14 23 33 42 45 67 98
  • 62. Sorting: Merge Sort page 62 © Dr. Jonathan (Yahya) Cazalas 67 45 23 14 6 33 98 42 67 45 23 14 6 33 98 42 45 23 14 98 23 98 45 14 67 6 33 42 67 6 33 42 23 98 45 14 67 6 42 33 14 23 45 98 6 33 42 67 6 14 23 33 42 45 67 98
  • 63. Sorting: Merge Sort page 63 © Dr. Jonathan (Yahya) Cazalas 67 45 23 14 6 33 98 42 6 14 23 33 42 45 67 98
  • 64. Sorting: Merge Sort page 64 © Dr. Jonathan (Yahya) Cazalas Sorting: Merge Sort  Merge Sort – Conceptual Understanding  To make the explanation easy, we said that the first step is to divide the array into two smaller arrays of about equal size  Then we recursively call Merge Sort on the first half of the array  Then we recursively call Merge Sort on the second half of the array.  Finally, we Merge.  However, this is not what happens in code!
  • 65. Sorting: Merge Sort page 65 © Dr. Jonathan (Yahya) Cazalas Sorting: Merge Sort  Merge Sort – Reality of the Code  However, in reality, we do NOT divide the array into two new arrays.  This is unnecessary and would take a lot of memory  What really happens?  There is only ONE array.  There are three steps: 1. Recursively Merge Sort the left half of the array. 2. Recursively Merge Sort the right half of the array. 3. Merge the two sorted halves together.
  • 66. Sorting: Merge Sort page 66 © Dr. Jonathan (Yahya) Cazalas Sorting: Merge Sort  Merge Sort – Psuedocode  Here’s the idea of what happens in the code: method MergeSort(array) { 1. MergeSort(left half of array) 2. MergeSort(right half of Array) 3. Merge }
  • 67. Sorting: Merge Sort page 67 © Dr. Jonathan (Yahya) Cazalas 13 6 21 18 9 4 8 20 0 7 4 6 8 9 13 18 20 21 0 7 13 6 21 18 0 3 9 4 8 20 4 7 6 13 18 21 0 3 4 8 9 20 4 7 13 6 0 1 21 18 2 3 9 4 4 5 8 20 6 7 6 13 0 1 18 21 2 3 4 9 4 5 8 20 6 7 13 0 6 1 21 2 18 3 9 4 4 5 8 6 20 7 Sorting: Merge Sort (real example)
  • 68. Sorting: Merge Sort page 68 © Dr. Jonathan (Yahya) Cazalas Brief Interlude: FAIL Picture
  • 69. Sorting: Merge Sort page 69 © Dr. Jonathan (Yahya) Cazalas Daily Bike Fail
  • 70. Sorting: Merge Sort page 70 © Dr. Jonathan (Yahya) Cazalas Weekly Bike Fail
  • 71. Sorting: Merge Sort page 71 © Dr. Jonathan (Yahya) Cazalas Sorting: Merge Sort  Merge Sort Code public void MergeSort(int values[], int start, int end) { int mid; // Check if our sorting range is more than one element. if (start < end) { mid = (start+end)/2; // Sort the first half of the values. MergeSort(values, start, mid); // Sort the last half of the values. MergeSort(values, mid+1, end); // Put it all together. Merge(values, start, mid+1, end); } }
  • 72. Sorting: Merge Sort page 72 © Dr. Jonathan (Yahya) Cazalas Sorting: Merge Sort  Merge Code  This code is longer  And a bit convoluted  But all it does it Merge the values from two arrays into one larger array  Of course, keeping the items in order  Just like the example shown earlier in the slides  You can find Merge code in the book and online  Or you can code it up yourself from the example shown earlier in the slides
  • 73. Sorting: Merge Sort page 73 © Dr. Jonathan (Yahya) Cazalas Sorting: Merge Sort  Merge Sort Analysis  Again, here are the steps of Merge Sort: 1) Merge Sort the first half of the list 2) Merge Sort the second half of the list 3) Merge both halves together  Let T(n) be the running time of Merge Sort on an input size n  Then we have:  T(n) = (Time in step 1) + (Time in step 2) + (Time in step 3)
  • 74. Sorting: Merge Sort page 74 © Dr. Jonathan (Yahya) Cazalas Sorting: Merge Sort  Merge Sort Analysis  T(n): running time of Merge Sort on input size n  Therefore, we have:  T(n) = (Time in step 1) + (Time in step 2) + (Time in step 3)  Notice that Step 1 and Step 2 are sorting problems also  But they are of size n/2  And the Merge function runs in O(n) time  Thus, we get the following equation for T(n)  T(n) = T(n/2) + T(n/2) + O(n)  T(n) = 2T(n/2) + O(n) …we are halving the input
  • 75. Sorting: Merge Sort page 75 © Dr. Jonathan (Yahya) Cazalas Sorting: Merge Sort  Merge Sort Analysis  T(n) = 2T(n/2) + O(n)  For the time being, let’s simplify O(n) to just n  T(n) = 2T(n/2) + n  and we know that T(1) = 1  So we now have a Recurrence Relation  Is it solved?  NO!  Why?  Damn T’s!
  • 76. Sorting: Merge Sort page 76 © Dr. Jonathan (Yahya) Cazalas Sorting: Merge Sort  Merge Sort Analysis  T(n) = 2T(n/2) + n and T(1) = 1  So we need to solve this, by removing the T(…)’s from the right hand side  Then T(n) will be in its closed form  And we can state its Big-O running time  We do this in steps  We replace n with n/2 on both sides of the equation  We plug the result back in  And then we do it again…till a “light goes off” and we see something
  • 77. Sorting: Merge Sort page 77 © Dr. Jonathan (Yahya) Cazalas Sorting: Merge Sort  Merge Sort Analysis  T(n) = 2T(n/2) + n  Do you know what T(n/2) equals  Does it equal 2,125 operations? We don’t know!  So we need to develop an equation for T(n/2)  How?  Take the original equation shown above  Wherever you see an ‘n’, substitute with ‘n/2’  T(n/2) = 2T(n/4) + n/2  So now we have an equation for T(n/2) and T(1) = 1
  • 78. Sorting: Merge Sort page 78 © Dr. Jonathan (Yahya) Cazalas Sorting: Merge Sort  Merge Sort Analysis  T(n) = 2T(n/2) + n  T(n/2) = 2T(n/4) + n/2  So now we have an equation for T(n/2)  We can take this equation and substitute it back into the original equation  T(n) = 2T(n/2) + n = 2[2T(n/4) + n/2] + n  now simplify  T(n) = 4T(n/4) + 2n  Same thing here: do you know what T(n/4) equals?  No we don’t! So we need to develop an eqn for T(n/4) and T(1) = 1
  • 79. Sorting: Merge Sort page 79 © Dr. Jonathan (Yahya) Cazalas Sorting: Merge Sort  Merge Sort Analysis  T(n) = 2T(n/2) + n  T(n/2) = 2T(n/4) + n/2  T(n) = 4T(n/4) + 2n  Same thing here: do you know what T(n/4) equals?  No we don’t! So we need to develop an eqn for T(n/4)  Take the eqn above and again substitute ‘n/2’ for ‘n’  T(n/4) = 2T(n/8) + n/4  So now we have an equation for T(n/4)  We can take this equation and substitute it back the equation that we currently have in terms of T(n/4) and T(1) = 1
  • 80. Sorting: Merge Sort page 80 © Dr. Jonathan (Yahya) Cazalas Sorting: Merge Sort  Merge Sort Analysis  T(n) = 2T(n/2) + n  T(n/2) = 2T(n/4) + n/2  T(n) = 4T(n/4) + 2n  T(n/4) = 2T(n/8) + n/4  So now we have an equation for T(n/4)  We can take this equation and substitute it back the equation that we currently have in terms of T(n/4)  T(n) = 4T(n/4) + 2n = 4[2T(n/8) + n/4] + 2n  Simplify a bit  T(n) = 8T(n/8) + 3n and T(1) = 1
  • 81. Sorting: Merge Sort page 81 © Dr. Jonathan (Yahya) Cazalas Sorting: Merge Sort  Merge Sort Analysis  So now we have three equations for T(n):  T(n) = 2T(n/2) + n  T(n) = 4T(n/4) + 2n  T(n) = 8T(n/8) + 3n  So on the kth step/stage of the recursion, we get a generalized recurrence relation:  T(n) = 2kT(n/2k) +kn  Whew! So now we’re done right?  1st step of recursion  2nd step of recursion  3rd step of recursion  kth step of recursion Wrong!
  • 82. Sorting: Merge Sort page 82 © Dr. Jonathan (Yahya) Cazalas Sorting: Merge Sort  Merge Sort Analysis  So on the kth step/stage of the recursion, we get a generalized recurrence relation:  T(n) = 2kT(n/2k) +kn  We need to get rid of the T(…)’s on the right side  Remember, we know T(1) = 1  So we make a substitution:  Let n = 2k  and also solve for k  k = log2n  Plug these back in…
  • 83. Sorting: Merge Sort page 83 © Dr. Jonathan (Yahya) Cazalas Sorting: Merge Sort  Merge Sort Analysis  So on the kth step/stage of the recursion, we get a generalized recurrence relation:  T(n) = 2kT(n/2k) +kn  Let n = 2k  and also solve for k  k = log2n  Plug these back in…  T(n) = 2log2nT(n/n) +(log2n)n  T(n) = n*T(1) + nlogn = n + n*logn  So Merge Sort runs in O(n*logn) time
  • 84. Sorting: Merge Sort page 84 © Dr. Jonathan (Yahya) Cazalas Sorting: Merge Sort  Merge Sort Summary  Avoids all the unnecessary swaps of n2 sorts  Uses recursion to split up a list until we get to “lists” of 1 or 0 elements  Uses a Merge function to merge (“sort”) these smaller lists into larger lists  Is MUCH faster than n2 sorts  Merge Sort runs in O(nlogn) time
  • 85. Sorting: Merge Sort page 85 © Dr. Jonathan (Yahya) Cazalas Sorting: Merge Sort WASN’T THAT THE COOLEST!
  • 86. Sorting: Merge Sort page 86 © Dr. Jonathan (Yahya) Cazalas Daily Demotivator
  • 87. College of Computing & Information Technology King Abdulaziz University CPCS-204 – Data Structures I Sorting: Merge Sort