Chapter 1.2 Algorithm Concepts
Chapter 1.2 Algorithm Concepts
Bedasa Wayessa
[email protected]
Bedasa Wayessa
[email protected]
– Therefore, Ssum(n)= 0.
float sum(float list[], int n) {
float tempsum = 0;
for (int i =0; i < n; i++)
tempsum += list[i];
return tempsum;
}
Data Structures and Algorithms - CoSc2091 22
Complexity Analysis:Time Complexity
Time complexity is a function describing the amount of time an
algorithm takes in-terms of the amount of input to the algorithm.
It is the amount of computer time it needs to run to completion.
The time is measured by counting the number of key operations:
– in sorting and
– searching algorithms, for example, the number of comparisons.
It is most important one which does not use real time.
The time complexity is of two types such as
Compilation time and Runtime
Compilation Time: the amount of time taken by the compiler to
compile an algorithm.
x x+y
this statement is 1.
for i 1 to n do
x x+y
this statement is n.
repeat
for i 1 to n do
for j 1 to n do
x x +y this statement is n2.
repeat
repeat
– Loop rule: find the order of the loop by multiplying the order of
the body of the loop by the number of times the loop will execute.
– In this case, however, the body of the loop is a method call.
– Therefore, we must determine the order of the method before we
can determine the order of the code segment.
– Let’s suppose that the purpose of the method is to print the sum
of the integers from 1 to n each time it is called.
Data Structures and Algorithms - CoSc2091 42
How to Determine Complexities
5. Statements with method calls:
– Let’s suppose that we have the following segment of code:
for (int count = 0; count < n; count++) {
printsum(count); //method called
}
void printsum(int count) {
int sum = 0;
for (int i = 1; i < count; i++){
sum += i;
}
cout<<sum;
}
– What is the time complexity of this printsum method?
– The loop, on the other hand, is O(n), and thus the method itself is O(n).
void swap(x, y) {
int temp;
t = x; 1 f(n) = 3
x = y; 1 sum -constant running time.
y = temp; 1
=>f(n)=O(1)
}
1<logn < n < nlogn < 𝒏𝒏𝟐𝟐 <n 𝒏𝒏𝟑𝟑 <…< 𝟐𝟐𝒏𝒏 < 𝟑𝟑𝒏𝒏 <…< 𝒏𝒏𝒏𝒏
Exponential