Chap 3 - Brute Force (Merging)
Chap 3 - Brute Force (Merging)
Lecture # 2
Output Sorted array C=(c1, c2,…, cn+m) of n+m elements such that:
(i)ci ∊ C belongs to A or B, ∀ 1 ≤ i ≤ n+m.
(ii)ai and bj appear exactly once in C, ∀ 1 ≤ i ≤ n and 1 ≤ j ≤ m.
A B C
1 1 1
2 2 2
i
p
q j
n
w k
n+m
1 2 3 Begin
p=q=w=1 .1
B 2 4 4 While p ≤ n and q ≤ m do .2
if ap ≤ bq Then
cw = ap , p=p+1, w=w+1
else cw = bq , q=q+1, w=w+1
If p > n then C(cw, cw+1,…, cn+m)=B(bq, bq+1,…, bm) .3
if q> m then C(cw, cw+1,…, cn+m)=A(ap, ap+1,…, an)
.End
p q w p≤ n q≤m ap ≤ bq
1 1 1 √ √ √ C=(1)
2 2 √ √ X C=(1,2)
2 3 √ √ √ C=(1,2,4)
3 4 √ √ X C=(1,2,4,4)
3 5 √ √ X C=(1,2,4,4,4)
94 6 √ X Dr. Hazem
Terminate whileM. Bahig 03:44