Beruflich Dokumente
Kultur Dokumente
Divide–and–Conquer
Merge Sort
Quick Sort
Divide–and–Conquer
1. Divide
If the input size is smaller
Solve the problem directly using a
straightforward method.
Otherwise
Divide the input data into two or more disjoint
subsets.
2. Recur
Recursively solve the subproblems associated with the
subsets.
3. Conquer
Take the solutions to the subproblems.
Merge them into a solution to the original problem.
D. S. R. Murthy DSA-6 Sorting, Sets, and Selection 2
Merge Sort
Based on Divide–and–Conquer algorithmic design
pattern.
Sequence S with n elements.
1. Divide in half
Split list equally
2. Recur 2. Recur
S1 S2
3. Merge
1. Divide
If S has zero or one element
Return S (already sorted)
Otherwise (S has atleast two elements)
Remove all the elements from S.
Put them into two sequences of about half of the
elements S1 and S2.
S1 First n/2 elements of S.
S2 Remaining n/2 elements of S.
2. Recur
Recursively sort S1 and S2.
3. Conquer
Put the elements back into S by merging the sorted
sequences S1 and S2 into a sorted sequence.
D. S. R. Murthy DSA-6 Sorting, Sets, and Selection 3
Example:
85 24 63 45 17 31 96 50
85 24 63 45 17 31 96 50
85 24 63 45 17 31 96 50
24 45 63 85 17 31 50 96
24 85 45 63 17 31 50 96
85 24 63 45 17 31 96 50
D. S. R. Murthy DSA-6 Sorting, Sets, and Selection 4
Set
Container of distinct objects.
Union
Intersection
Subtraction
Implementation of Union
Input
Two sets with ordered sequences.
Output
Set with an ordered sequence.
• If a < b
Copy a to the output sequence
Advance to the next element of A.
• If a = b
Copy a to the output sequence
Advance to the next elements of A and B.
• If a > b
Copy b to the output sequence
Advance to the next element of B.
D. S. R. Murthy DSA-6 Sorting, Sets, and Selection 5
Quick Sort
Sorts a sequence S
using Divide-and-conquer approach.
1. Split using pivot x.
E (=x)
2. Recur 2. Recur
L (<x) L (>x)
3. Concatenate
1. Divide
If S has zero or one element
Return S (already sorted)
Otherwise (S has atleast two elements)
Select a specific (last) element x (Pivot) from S.
Remove all the elements from S.
Put them into three sequences:
• L, storing the elements in S < x.
• E, storing the elements in S = x.
• G, storing the elements in S > x.
2. Recur
Recursively sort sequences L and G.
3. Conquer
Put the elements back into S in order by
inserting the elements of L,
inserting the elements of E,
inserting the elements of G.
D. S. R. Murthy DSA-6 Sorting, Sets, and Selection 6
Example:
24 45 17 31 85 63 96
24 17 45 85 63
24 85
17 24 31 45 63 85 96
17 24 45 63 85
24 85
D. S. R. Murthy DSA-6 Sorting, Sets, and Selection 7
xi < xj
xa < xb xc < xd
| |
n!