Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

JIS University

Design and Analysis of Algorithms Lab Manual


Even Semester 2021[Jan to April]

Problem 1: Implement Binary Search (Recursive & Iterative) using Divide and Conquer
approach

10 20 30 40 50 60 70 80

Search Value = 80
Linear Search Time Complexity = size of array = O (n) = O (8)

Apply Divide and Conquer Approach


1. Divide the problem into smaller sub-problems
2. Solve each sub-problem
3. Combine all the solutions

10 20 30 40 50 60 70 80
0 1 2 3 4 5 6 7

Left = 0
Right = 7
FIRST:

´
Mid = (¿¿)/2 = (0 + 7)/2 ~ 4

Key = Array [Mid]= 80≠ 50

Key > Array[Mid] ........Left = Mid+1=4+1=5


Key < Array[Mid]..........Right = Mid-1 = 4-1 =3

10 20 30 40 50 60 70 80
0 1 2 3 4 5 6 7

SECOND:
JIS University

Design and Analysis of Algorithms Lab Manual


Even Semester 2021[Jan to April]

´
Mid = (¿¿)/2 = (5 + 7)/2 ~ 6

Key = Array [Mid]= 80≠ 70

Key > Array[Mid] ........Left = Mid+1=6+1=7


Key < Array[Mid]..........Right = Mid-1 = 6-1 =5

THIRD:
10 20 30 40 50 60 70 80
0 1 2 3 4 5 6 7

´
Mid = (¿¿)/2 = (7 + 7)/2 ~ 7

Key = Array [Mid]= 80≠ 80 

T (n) = T(n/2) + 1
= T(n/22) + 2
= .................................
= T(n/2i) + i
= T(1) + log2n

n/2i=1=>i = log2n

log28 = 3
JIS University

Design and Analysis of Algorithms Lab Manual


Even Semester 2021[Jan to April]

Problem 2: Implement Merge Sort using Divide and Conquer approach

Theory:
Divide and Conquer
1. N-element sequence which is divided into two-subsequences of N/2 size
(Divide)...Definition is recursive
2. Sort the two subsequences recursively using merge sort (Conquer)
3. Merge all the solutions to get the total solution

Merge (A, p, q, r):


i=k=p;
J=q+1
While ( i<=q AND j<=r): cn
{
if A(i) < A(j) {B[k] = A[i]; k++; i++;}
else {B[k]= A[j]; k++;j++ }
}
While(i<=q){B[k++]=A[i++];} cn
While(j<=r){B[k++]=A[j++];} c
}

MergeSort (A, p, r):


q = (p + r)/2;
if (p<r)
{
MergeSort (A, p, q);
MergeSort (A, q+1, r);
JIS University

Design and Analysis of Algorithms Lab Manual


Even Semester 2021[Jan to April]

Merge(A, p, q, r);
}

You might also like