Algorithms class notes
Algorithms class notes
1.Normal Multiplication:
Multiply
86415
74070
61725
49380
37035
------------
426729615
-------------
Input:
Integers X and Y
No. of digits : n
Output:
Z=X*Y
23=2 * 10 + 3
2345=23 * 10 ^2 +45
X=235678=235 * 10 ^ 3+ 678
Y=435890=435 * 10 ^3 + 890
=(235*435)10^6+(235*890+678*435)10^3+678*890
No. of multiplications=6
A= 4
B=2
Logba= Log24=2
N^ Logba=n^2
F(n)=n
T(n)=O(N^ Logba)=O(n^2)
3. Karastuba method:
X=235678=235 * 10 ^ 3+ 678=a.10^(n/2) + b
A=235 b=678
C=435 d=890
Z= X * Y=
U=(a+b).(c+d)
V=a.c
W=b.d
X*Y=V10^n+(U-V-W)10 ^(n/2)+W
No. of multiplications=5
A= 3
B=2
Logba= Log23=1.59
N^ Logba=n^1.59
F(n)=n
Case 1 of master method epsilon=0.59
T(n)=O(N^ Logba)=O(n^1.59)
X=1235678=1235 * 10 ^ 3+ 678=a.10^(n/2) + b
n/2=(n/2
karastuba(x,y,n)
If (n==1)
Return(x*y);
i=n/2
U=karastuba((a+b),(c+d),i)
V=karstuba(a,c,i)
W=karastuba(b,d,i)
Return(v.10^n+(u-v-w)10^i+w)
(a+b).(c+d)=a.c.10^n+(a.d+b.c).10^n/2+b.d
Graph
G(V,E)
//variables
Int g[5][5],I,j;
For(i=0;i<5;i++)
For(j=0;j<5;j++
Scanf(“%d”,&g[i][j]);
For(i=0;i<5;i++)
Printf(“\n”);
For(j=0;j<5;j++)
printf(“%d”,g[i][j]);
}
Adjancency list
Struct node
Int data;
12345
13245
Bfs
12345
13245
bfs
75
1. Unvisited 2 7 5 10 6 9 11 4
2 7 5 10 6 9 11 4
Bfs
Visit a node
First adjacent
0 1 1 0 0
1 0 1 1 0
1 1 0 0 1
0 1 0 0 1
0 0 1 1 0
V1 V2 V3 V4 V5
Queue initialisatioin
Visit
1 2 3 4 5
0 0 0 0 0
12345
Add adjacent
T(n)=3t(n/4)+n^2 =O(n^2)
N^(loga)= F(n)
Log3<1+e 2
Log4=1
level Size of the Steps in the node No. of Total steps in the
subproblem subproblems level
0 root n N^2 1 N^2
1 n/4 (n/4)^2 3 3(n/4)^2
2 n/16=n/4^2 (n/16)^2 9=3^2 9(n/16)^2
3 n/64=n/4^3 (n/64)^2 27 27(n/64)^2
…
k n/4^k (n/4^k)^2 3^k 3^k(n/4^k)^2
Total steps required by the algorithm=N^2+3(n/4)^2+9(n/16)^2+27(n/64)^2+…+3^k(n/4^k)^2
=O(n^2)
n/4^k=1
4^k=n
K=log4n
T(n)=3T(n/5)+n
T(n)=T(n/3)+T(2n/3)+n
Graph:
V={v1,v2,v3,v4,v5,v6}
E={(v1,v2,6)
Source vertex- v1
Output
Destinations
V1V2
V1V3
V1V4
V1V5
V1V6
step A=source B C D E Shortest path
1 0 infinity infinity infinity infinity
2 0 10 3 infinity infinity a-c 3
3 acb 7 acd 8 a-ce 5 a-ce 5
4 A10 Ainfi aCb=7
aCb=7 aCd=11
einfini E14
5 Ainfi aCbd=9
C11
E14
aCbd=9
t
Session 6
Log44=1
Log43=0.8
5. T(n)=2T(n/2)+nlogn
6. T(n)=4T(n/2)+nlogn
A=4 b=2 n^logba=n^log24=n^2
F(n)=nlogn
N^2 > nlogn case1 O(n^2)
7. T(n)=2T(n/2)+n/logn
A=2 b=2 n^logba=n^log22=n^1
n^logba is asymptotically greater than f(n)
But n^logba is not polynomially greater than f(n)
N > n/logn by a factor or n/( n/logn)= n.logn/n= logn
8. T(n)=T(n/2)+T(3n/2)+ O(n)
Since the size of the sub problems are not same master method cannot be applied
1. Substitution method
2. Iteration method
3. Recurrence tree method
4. Master method
//input : array and element to be searched
Master method:
Merge sort
Array size n
No of subarrays 2
T(n)=a.T(n/b) + f(n)
Asymptotically
Asymptotically
Asymptotically
polynomically greater
Asymptotically
polynomially greater
polynomially greater
Recurrence tree:
Tree: