Merge sort
-
Upload
sindhoo-oad -
Category
Technology
-
view
326 -
download
1
description
Transcript of Merge sort
MERGE SORTPRESENTED BY: SINDHOO OAD
Merge Sort
Merge sort is based on the divide-and-conquer paradigm.
To sort A[p .. r]:
1. Divide Step
If a given array A has zero or one element, simply return; it is already sorted. Otherwise, split A[p .. r] into two subarrays A[p .. q] and A[q + 1 .. r], each containing about half of the elements of A[p .. r]. That is, q is the halfway point of A[p .. r].
2. Conquer Step
Conquer by recursively sorting the two subarrays A[p .. q] and A[q + 1 .. r].
3. Combine Step
Combine the elements back in A[p .. r] by merging the two sorted subarrays A[p .. q] and A[q + 1 .. r] into a sorted sequence. To accomplish this step, we will define a procedure MERGE (A, p, q, r).
Note that the recursion bottoms out when the subarray has just one element, so that it is trivially sorted.
The following figure tells to continue expanding until the problem sizes get down to 1.
subproblem 2 of size n/2
subproblem 1 of size n/2
a solution to subproblem 1
a solution to subproblem 2
a problem of size n
a solution tothe original problem
Example 1:1 2 3 4 5 6 7 8
q = 462317425
1 2 3 4
7425
5 6 7 8
6231
1 2
25
3 4
74
5 6
31
7 8
62
1
5
2
2
3
4
4
7 1
6
3
7
2
8
6
5
Divide
Conquer and
Merge
1
5
2
2
3
4
4
7 1
6
3
7
2
8
6
5
1 2 3 4 5 6 7 8
76543221
1 2 3 4
7542
5 6 7 8
6321
1 2
52
3 4
74
5 6
31
7 8
62
Example 2:99 6 86 15 58 35 86 4 0
99 6 86 15 58 35 86 4 0
99 6 86 15 58 35 86 4 0
99 6 86 15 58 35 86 4 0
99 6 86 15 58 35 86 4 0
86 1599 6 58 35 86 4 0
99 6 86 15 58 35 86 4 0
99 6 86 15 58 35 86 4 0
86 1599 6 58 35 86 4 0
99 6 86 15 58 35 86 4 0
99 6 86 15 58 35 86 4 0
99 6 86 15 58 35 86 4 0
86 1599 6 58 35 86 4 0
99 6 86 15 58 35 86 4 0
4 0
99 6 86 15 58 35 86 0 4
4 0Merge
15 866 99 58 35 0 4 86
99 6 86 15 58 35 86 0 4
Merge
Merge Sort Example
6 15 86 99 0 4 35 58 86
15 866 99 58 35 0 4 86
Merge
0 4 6 15 35 58 86 86 99
6 15 86 99 0 4 35 58 86
Merge
Pros:
It is a stable sort, and there is no worst-case scenario.
It is faster, the temp array holds the resulting array until both left and right sides are merged into the temp array, then the temp array is appended over the input array.
It is used in tape drives to sort data - its good with parallel processing.
Cons:
The memory requirement is doubled.
Takes longer to merge because if the next element is in the right side then all of the elements must be moved down.