Merge sort

18
MERGE SORT PRESENTED BY: SINDHOO OAD

description

 

Transcript of Merge sort

Page 1: Merge sort

MERGE SORTPRESENTED BY: SINDHOO OAD

Page 2: Merge sort

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].

Page 3: Merge sort

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.

Page 4: Merge sort

The following figure tells to continue expanding until the problem sizes get down to 1.

Page 5: Merge sort

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

Page 6: Merge sort

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

Page 7: Merge sort

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

Page 8: Merge sort

Example 2:99 6 86 15 58 35 86 4 0

Page 9: Merge sort

99 6 86 15 58 35 86 4 0

99 6 86 15 58 35 86 4 0

Page 10: Merge sort

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

Page 11: Merge sort

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

Page 12: Merge sort

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

Page 13: Merge sort

99 6 86 15 58 35 86 0 4

4 0Merge

Page 14: Merge sort

15 866 99 58 35 0 4 86

99 6 86 15 58 35 86 0 4

Merge

Page 15: Merge sort

Merge Sort Example

6 15 86 99 0 4 35 58 86

15 866 99 58 35 0 4 86

Merge

Page 16: Merge sort

0 4 6 15 35 58 86 86 99

6 15 86 99 0 4 35 58 86

Merge

Page 17: Merge sort

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.

Page 18: Merge sort

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.