Professional Documents
Culture Documents
Data Structures and Algorithms
Data Structures and Algorithms
Data Structures and Algorithms
Algorithms
Introduction
• Data Structures
– Arrays
– Lists
– Trees
– Graphs
• Algorithms
Abu Ja'far Mohammed Ibn Musa al-Khowarizmi
Algorithms
Example
• 1. Algorithm Max(A,n)
• 2. // A is an array of size n
• 3. {
• 4. Result := A[1];
• 5. for i=2 to n do
• 6. If A[i] > Result then Result :=
A[i];
• 7. return Result;
• 8. }
What are Algorithms
Satisfy the criteria
1.Input
2.Output
3.Definiteness
4.Finiteness
5.Effectiveness
6.Generality
Write an algorithm to find the speed at which the
electrons travel.
Areas of Study
• How to Devise
• How to Validate
• How to Analyze
• How to Test
Recursion
Program A
Calls A
Program A
• Indirect Recursive Calls B
Program B
Calls A
Whose Code is Better ?
Program
• Space Complexity
Program
CPU
• Time Complexity
Space Complexity
S(P) = c + Sp
c = Fixedpart
Sp = Variable part.
Example
Algorithm ex1(a,b,c)
{
return a+b+c;
}
}
Example
Algorithm ex3(a,n)
{
If (n<= 0) then return 0.0;
else return ex3(a,n-1) + a[n];
}
Each function call needs:
One Location for n
One Location for a[n]
One location for the return address
Time Complexity
Algorithm ex1(a,b)
{
return a+b;
}
}
return s;
}
Example
Algorithm ex2(a,n) Count the number of
{ Statements
s := 0.0;
count = count+1;
for i : = 0 to n do
{
count=count+1; Count the number of times
s : = s + a[i]; the for loops is executed
count=count + 1;
}
count = count +1 ;
count = count +1 ;
return s;
}
Example
Each Function call has 2
Algorithm ex3(a,n) statements.
{
count = count + 1
If (n<= 0) then
{
count = count + 1;
return 0.0; How many times is the
} recursion called ?
else
{
count = count + 1
return ex3(a,n-1) + a[n];
}
Try it out
O(n3 )
Asymptotic Notation
• Big Oh
• Omega
Big Oh
Upper Bound
Big Oh
f(n) is O(g(n) ) iff
f(n) <= c* g(n) for all n> n0
Graphical Represntation
f(N)
running time
N
n0
Example
cg(N)
running time
N
n0
Example