Introduction To Algorithm
Introduction To Algorithm
That is , we are reading a value for variable a. We are reading another value for
another variable b.
So, every statement must have a single meaning that is only one meaning. It
means every statement must be unambiguous. There should be no ambiguity, it
should be very clear.
Like, if you are writing a program and if you will say while(1) and if
you here print something, then this while(1) is always true.
while (1)
{
……
……
}
Effectiveness : It should perform that task for which you have written
that algorithm. It should be effective.
Example : Take sum of 2 numbers and here you will write sum = a +
b and here you can print sum.
Start
Read a
Read b
Sum = a + b
Print Sum
Stop
Output of this algorithm would be obviously the sum of these 2
numbers. That means, it is effective and it is not containing any
unnecessary statements, like here
Start
Read a
Read b
Read c
Sum = a + b
Print Sum
Stop
Input / Output
Calculation
Decision
Flow lines
Start
Input m1,
m2, m3, m4
Total = m1 + m2 + m3 + m4
Average = Total / 4
True False
If Average < 50
Print “Fail”
Print “Pass”
Stop
Here, you can see each instruction is specified in some block which is
also we call it as a graphical representation.
Pseudo - Code Method : In this method, we should typically
describe Algorithm as programs which resembles language like C. So,
we should typically describe algorithms like, why we are writing this
algorithm. Simply, in the next step we want to implement it as a
program.
Now, how the programming will be there. So, if you see how the
program is, then according to that if you make the algorithm as a
sequence of steps, then it is easy in the next step to implement it as a
program.
Pseudocode Conventions : Pseudocode convention means, how you
can represent the algorithm. What are the rules are there in the
Pseudocode convention.
1. Comments begin with forward slash [//] and continue until the
end of the line.
If you want to write any comment like in C – Language. There
are Single – Line Comments and Multi – Line Comments.
For Single – Line Comments you will use two forward slash [//].
For Multi – Line Comment you will use /* Multi – Line
Comment*/.
1. for I := 1 to 10 step 2 do
{
}
I = 1, 3, 5, 7, 9
2. for I := 1 to 10 do
{
}
I = 1,2,3,4,5,6,7,8,9,10
Case Statement
Case
{
: <condition 1> : <statement 1>
.
.
: <condition n> : <statement n>
else : <statement n+1>
}
In switch case statement, none of the case labels are satisfied there
you’ll write default statement. Here you will write else statement
n + 1 is executed and the case statement is exited. The else clause is
optional.
Input and Output are done using the instructions read and write . No
format is used to specify the size of input or output quantities.
Algorithm Max (A , n)
//A is an array of size n
{
Result := A[1];
for i := 2 to n do
if A[i] > Result then
Result := A[i];
return Result;
}
In this algorithm named max, A and n are procedural parameters .
Result and i are local variables.
Finally, combine the Base Case and General Case into an algorithm.
Recursive Algorithm for Factorial of a Number:
Algorithm Factorial(n)
{
if (n == 0)
return 1;
else
return (n * Factorial(n – 1));
}
How much time that an algorithm requires for its execution is nothing
but Time Complexity.
Key Element : 40
As the array is exhausted, so we can say that here the Key Element is
not found. While searching an element using Linear Search, if the key
element is found at first position, so this is nothing but Best Case
Time Complexity. Here, the algorithm requires one unit of time for
comparing the element.
List of Elements : 10 20 30 40 50
Key Element : 50
Average Case means if the key element found at some 2 nd place or 3rd
place or 4th place then we can say that it is Average Case Time
Complexity.
List of Elements : 10 20 30 40 50
Key Element : 30
Example :
Now, let us calculate the Time Complexity for the above algorithm.
Now, let us consider the for loop, how many times the condition will
be executed.
Let n = 3
Initial value of i = 0; 0 < 3 [True] . So, Step Count is 1.
Next i value is 1 ; 1 < 3 [True]. So, Step Count is 2.
Next i value is 2 ; 2 < 3 [True]. So, Step Count is 3.
Next i value is 3 ; 3 < 3 [False]. So, Step Count is 4.
Since n = 3, and the condition i < n will be executed for 4 times i.e.,
n + 1 times.
How many times the body of the loop will be executed? The body of
the loop will be executed for n times.
Now, we have to add all the step count values. This gives us
1 + n + 1 + n + 1 = 2n + 3.
Example :
Now, we have to calculate the Time and Space Complexity for the
above algorithm.
So, we have to consider only the higher order exponent that is n 2 and
we need to ignore the constant multiplier. The Time Complexity for
the above algorithm is O(n2).
Asymptotic Notations
Asymptotic Notations are mainly useful to calculate Time Complexity
of an algorithm.
By using Asymptotic Notations we can calculate
Best Case Time Complexity
Worst Case Time Complexity
Average Case Time Complexity
There are 5 types of Asymptotic Notations as follows:
1. Big Oh Notation
2. Big Omega Notation
3. Theta Notation
4. Little oh Notation
5. Little Omega Notation
Big Oh Notation
Big Oh notation is represented by O.
Big Oh notation mainly represents the Upper bound of algorithm’s
running time.
By using Big Oh notation we can calculate maximum amount of time
that an algorithm requires for its execution.
Big Oh notation is mainly useful in order to calculate the Worst Case
Time Complexity of an algorithm.
Definition of Big Oh notation
Let f(n), g(n) be two non – negative functions then f(n) = O(g(n)) if
there exists two positive constants c, n0 such that f(n) <= c * g(n), for
all n > n0.
X – axis represents n where n is the number of elements.
Y – axis represents t where t is the time.
If n > n0 then we can say that f(n) <= c *g(n) before that it may be
either less than or greater than c * g(n).
Example :
Let f(n) = 3n + 2 ; g(n) = n then we have to prove f(n) = O(g(n)).
So, in order to prove f(n) = O(g(n)) we have to satisfy this condition
f(n) <= c * g(n), for all n > n0.
3n + 2 <= c * n
Let n = 1; c =3
By Substituting the values we get
3 + 2 <= 3 * 1
5 <= 3 [False]
So, n should be greater than 3.
Let n0 = 1; c= 4, then n is represented as n0.
By substituting the values, we get
5 <= 4 [False]
Let n0 = 2; c= 4 then 8 <= 8 [True]
Let n0 = 3; c= 4 then 11 <= 12 [True].
n0 value should be greater than 2 ie n0 > 2.
So, we can say that this condition is true f(n) <= c * g(n), for all n > 2
and c = 4
Prove that 2n2 = O(n3) where f(n) = 2n2 and g(n) = n3.
f(n) <= c * g(n)
2n2 <= c * n3
Divide n2 on both sides, we get
2 <= c*n
n = 1 ; c =2
Big Omega Notation :
Big Omega Notation is represented by Ὼ.
Big Omega notation mainly represents lower bound of algorithm’s
running time.
It mainly represents minimum amount of time that an algorithm
requires for its execution.
Big Omega notation is mainly useful in order to calculate Best Case
Time Complexity of an algorithm.
Definition of Big Omega Notation
Let f(n), g(n) be two non – negative functions then f(n) = Ὼ(g(n)) if
there exists two positive constants c, n0 such that f(n) >= c * g(n), for
all n > n0.
Graphical Representation of Big Omega Notation
If n > n0 then we can say that f(n) > c * g(n) before that f(n) value
may be less than c * g(n) or greater than c * g(n).
Example : f(n) = 3n + 2 ; g(n) = n we have to prove f(n) = Ὼ(g(n)).
In order to prove the above, we have to prove f(n) >= c * g(n) for all n
> n0.
By substituting the values of f(n) and g(n) we get
3n + 2 >= c * n
Let c= 1 then we get 3n + 2 >= n
Let n0 = 1, c = 1, then 5 >= 1 [True]
Let n0 = 2, c = 1, then 8 >= 2 [True]
So we can say that , n0 >= 1
Theta Notation :
Theta notation is represented as ɵ.
Theta notation mainly represents the Average Bound of algorithm’s
running time.
By using Theta notation we can calculate the Average amount of time
that an algorithm requires for its execution.
By using Theta notation we can calculate Average Case Time
Complexity.
Definition of Theta Notation
Let f(n), g(n) be two non – negative functions , then f(n) = ɵ(g(n)) if
there exists three positive constants c1, c2, n0 such that
c1 * g(n) <= f(n) <= c2 * g(n), for all n > n0.
Graphical Representation of Theta Notation
S
So, if a problem is large divide the problem into sub – problems and
solve those sub – problems and combine the solutions of sub –
problems to get the solution for main problem.
That means, if a problem cannot be solved if it is too big break it into
sub – problems and solve it.
If a sub – problem is also large , then do the same thing, apply Divide
and Conquer strategy on sub – problems also. If it is large again do
the same thing, break it into sub – problems and find a solution and
then combine the solution.
Whatever the problem is , the sub – problems be same as that
problem.
For example, if a problem is to Sort then the sub – problems should
also be Sort. Each and every sub – problem should be sort only. It
cannot convert into some other problem.
General Method for Divide and Conquer Strategy
DAC(P)
{
if (small(P))
{
S(P);
}
else
{
Divide P into P1, P2, … , Pk
Apply DAC(P1), DAC(P2),…
Combine(DAC(P1), DAC(P2),….)
}
}
Divide and Conquer upon a problem P. If the problem is small then
directly solve it. Yes, definitely there must be a solution for small
problem.
If it is large, divide the problem P into sub – problems P1, P2, … , Pk
and apply Divide and Conquer on each. This is recursive.
Then, whatever the solutions you get, you combine these solutions of
the results of Divide And Conquer(P1), DAC(P2) and so on, combine
them together to get the solution for the main problem.
In the above example, we can see that it is having a recursive property
so the procedures are recursive, the algorithms are recursive.
Example :
0 1 2 3 4 5 6 7 8 9
5 9 17 23 25 45 59 63 71 89
In the above example, the data in that array is sorted. If the data is not
sorted then you cannot apply Binary Search on that array. You have to
first the array then you can apply Binary Search for searching.
0 1 2 3 4 5 6 7 8 9
5 9 17 23 25 45 59 63 71 89
Key element = 59
Search for that data. Is this Key element = 59, present in this array or
not.
If present, your code should return where this 59 is present. That is,
the index at which this 59 is present.
Binary Search algorithm uses Divide and Conquer strategy. That
means, it is going to divide the array into two halves. That is, it
recursively Divide the array.
In this case, we’re going to find out the Middle element of the array.
So, we’re going to take two variables. First is left variable and left
variable is going to point to the start position of the array. Next is
right variable and right variable will be pointing to the last position of
the array.
0 1 2 3 4 5 6 7 8 9
5 9 17 23 25 45 59 63 71 89
L R
Left = 0 Right = 9
In this algorithm, we’re going to find out the mid position of the
array. From where, we’re going to divide the array into 2 halves.
How to find mid? Mid = Floor [(l + r) / 2] and we’re going to take the
floor value.
0 1 2 3 4 5 6 7 8 9
5 9 17 23 25 45 59 63 71 89
L R
Left = 0 Mid Right = 9
The data you want to find out is equal to the data at the mid position.
The data is less than the data which is at mid position.
The data you want to find out is greater than the data which is at mid
position.
So, now we can say that the data is present to the right of this mid.
0 1 2 3 4 5 6 7 8 9
5 9 17 23 25 45 59 63 71 89
L R
Left = 0 Mid Right = 9
Now, we’ve divided the array into 2 parts. How you can say that 59 is
present to the right of this mid? Because we know that the array is
sorted. If array is sorted, then all the data which is greater than 25
must be present to the right of this 2.
Now, we’re going to see in the right sub – array. We’ve divided our
search space.
If data > a[mid], then the left variable should be moved to index 5 .
That is to the right of the mid.
0 1 2 3 4 5 6 7 8 9
5 9 17 23 2545 59 63 71 89
L R
Mid Left=5 Right = 9
Our L = mid + 1. As ,we are going to work in the right sub – array
only.
0 1 2 3 4 5 6 7 8 9
5 9 17 23 25 45 59 63 71 89
L R
Left=5 Mid Right = 9
Now, check data = 59; Mid = 63; data < a[Mid]; 59 < 63
First, it will check data is equal to Mid. It is False. Here, the data is
less than the Mid value.
Now, we can say that data is present to the left of 63. If the data is
present to the left of mid, in that case left would be as it is i.e., L = 5.
The Right, R would be moved towards this side. Now, R = Mid – 1.
0 1 2 3 4 5 6 7 8 9
5 9 17 23 25 45 59 63 71 89
L R
Left=5 Mid Right=6
We again divide the array into two parts. That is why we recursively
divide the array into 2 parts until you find the element.
0 1 2 3 4 5 6 7 8 9
5 9 17 23 25 45 59 63 71 89
L R
Left=6 Mid Right=6
Mid = Floor [(6 + 6) / 2 ] = Floor [6] = 6
So, now we’re going to stop and you’re going to return mid. Return
Mid means you are going to return the index 6 where the data is
present.
If data is not present in the array. In that case, when you are going to
stop searching.
0 1 2 3 4 5 6 7 8 9
5 9 17 23 25 45 59 63 71 89
L R
Left = 0 Right = 9
Key element = 60
0 1 2 3 4 5 6 7 8 9
5 9 17 23 25 45 59 63 71 89
L R
Left = 0 Mid Right = 9
As, 60 > 25, so data is present to the right of 25. Then we are going to
move this left L, Left = Mid + 1.
0 1 2 3 4 5 6 7 8 9
5 9 17 23 25 45 59 63 71 89
L R
Mid Left=5 Right = 9
Left Right Mid
0 9 4
5 9 7
0 1 2 3 4 5 6 7 8 9
5 9 17 23 25 45 59 63 71 89
L R
Left=5 Mid Right = 9
Now, check is 60 != 63 [False]. 60 < 63 [True] .
Since the data < a[mid] then the data is present to the left of 63. In
that case, R = Mid – 1.
0 1 2 3 4 5 6 7 8 9
5 9 17 23 25 45 59 63 71 89
L R
Left=5 Mid Right=6
Now, check if data = a[mid], that is 60 != 45 [False].
60 > 45, then data would be to the right of mid. In that case, left L
will be moving to the right of the array. L = Mid + 1.
60 > 59 [True], it means that data is present to the right of that mid
element. Then we are going to move this L = Mid +1.
Pivot = 10
Quick sort algorithm is based on the Divide and Conquer technique.
In Divide and Conquer technique, this complete array would be
divided into sub – arrays, and dividing this array into sub – arrays is
known as partitioning.
That partition method of this array that process is known as the
backbone of the quick sort.
0 1 2 3 4 5 6
10 15 1 2 9 16 11
Pivot = 10
We are going to partition this array in a way such that all the elements
less than this pivot element would be on the left side of the pivot
element and all the elements greater than this pivot element would be
to the right side of this element.
If any element which is equal to this pivot element that element can
go either ways i.e. either to the left side of the array or to the right
side of the array.
0 1 2 3 4 5 6
10 15 1 2 9 16 11
Pivot = 10
Key
Partition 1 Pivot Partition 2
Values < Pivot Values > Pivot
Now, that we have found out the proper place for one element, and
now the above array is divided into 2 arrays.
Key
Partition 1 Pivot Partition 2
Values < Pivot Values > Pivot
One is called “Partition 1” i.e. the values less than the pivot element.
The other is all the elements greater than the pivot element are on the
right – side and is called as “Partition 2”.
In “Partition 1” we cannot say that values are in sorted order but the
main thing is that all the values to the left side are less than the pivot
element.
All the values to the right side i.e. “Partition 2” would be greater than
this pivot element.
We are going to choose pivot element on the left – side of the array
i.e. “Partition 1” again into two parts.
We are going to choose pivot element on the right – side of the array
i.e “ Partition 2” again into two parts and we are going to continue
this until we only one element left out.
2, 1, 9 or 9,1,2 10 15, 11, 16 or 16, 11,
15
0 1 2 3 4 5 6
2 1 9 10 15 11 16
Example
0 1 2 3 4 5 6 7 8
7 6 10 5 9 2 1 15 7
In the above array, it contains 9 elements and name of the array A and
index is from 0 – 8.
0 1 2 3 4 5 6 7 8
7 6 10 5 9 2 1 15 7
lb
ub
Pivot = a[0] = 7
Where lb is Lower bound of this array
ub is Upper bound of this array
Now, we have to find out the proper place for the pivot element such
that all the elements less than pivot element i.e. 7 should be on the left
side of the array and all the elements greater than pivot element i.e. 7
should be on the right side of the array.
0 1 2 3 4 5 6 7 8
7 6 10 5 9 2 1 15 7
start
end
start variable will be moving from left to right.
end variable will be moving from right to left.
If you find any element which is greater than this pivot element at that
element we are going to stop the ‘start’ variable otherwise we are
going to increment start variable.
Or
If you find any element which is less than or equal to this pivot
element, then we are going to increment start variable until we found
element greater than pivot element.
0 1 2 3 4 5 6 7 8
7 6 10 5 9 2 1 15 7
start
end
Pivot = 7 (7 <= 7 True)
0 1 2 3 4 5 6 7 8
7 6 10 5 9 2 1 15 7
start
end
(6 < = 7 True)
0 1 2 3 4 5 6 7 8
7 6 10 5 9 2 1 15 7
start
end
(10 <= 7 False)
0 1 2 3 4 5 6 7 8
7 6 7 5 9 2 1 15 10
start
end
0 1 2 3 4 5 6 7 8
7 6 7 5 9 2 1 15 10
start
end
(5 <= 7 True)
0 1 2 3 4 5 6 7 8
7 6 7 5 9 2 1 15 10
start
end
(9 <= 7 False)
0 1 2 3 4 5 6 7 8
7 6 7 5 9 2 1 15 10
start
end
(10 > 7 True)
0 1 2 3 4 5 6 7 8
7 6 7 5 9 2 1 15 10
start end
(15 > 7 True)
0 1 2 3 4 5 6 7 8
7 6 7 5 9 2 1 15 10
start end
(1 > 7 False)
Now, we are going to swap the elements 9 and 1. After swapping the
array would be.
0 1 2 3 4 5 6 7
8
7 6 7 5 1 2 9 15 10
start end
a[start] <= Pivot
(1 <= 7 True)
0 1 2 3 4 5 6 7
8
7 6 7 5 1 2 9 15 10
start end
a[start] <= Pivot
(2 <= 7 True)
0 1 2 3 4 5 6 7 8
7 6 7 5 1 2 9 15 10
start end
a[start] <= Pivot
(9 <= 7 False, We are going to stop here)
0 1 2 3 4 5 6 7 8
7 6 7 5 1 2 9 15 10
start end
a[end] > Pivot
(9 > 7 True, Decrement the end variable)
0 1 2 3 4 5 6 7
8
7 6 7 5 1 2 9 15 10
end start
a[end] > Pivot
(2 > 7 False, then we are going to stop here)
After that, we have to swap the elements, but we are not going to
swap the elements. Why ?
Because ‘start’ variable has crossed the ‘end’ variable so we are not
going to swap the elements.
We are going to follow the procedure swapping and all until we have
‘start’ is less than ‘end’.
At the point we got ‘start’ is greater than ‘end’ then we are not going
to swap.
Now, next step is we are going to swap this pivot element with the
element where end variable is available.
After swapping the array would be :
0 1 2 3 4 5 6 7
8
2 6 7 5 1 7 9 15 10
0 1 2 3 4 5 6 7 8
15 5 24 8 1 3 16 10 20
0 1 2
15 5 24 8 1
3 16 10 20
15 5 24
8 1 3 16 10
20
15 5
Now, we cannot further divide the sub – lists because each sub – list
is having 1 element.
Algorithm
Mergesort(A, lb, ub)
{
if (lb < ub)
{
mid = (lb + ub) / 2
Mergesort(A, lb, mid);
Mergesort(A, mid + 1, ub);
Merge(A, lb, mid, ub);
}
}
Merge(A, lb, mid, ub)
{
i = lb;
j = mid + 1;
k = lb;
while ((i <= mid) && (j <= ub))
{
if(a[i] <= a[j])
{
b[k] = a[i];
i++;
}
else
{
b[k] = a[j];
j ++;
}
k++;
}
if (i > mid)
{
while(j <= ub)
{
b[k] = a[j];
j++;
k++;
}
}
else
{
while (i <= mid)
{
b[k] = a[i];
i++;
k++;
}
}
for (k = lb; k <= ub; k++)
{
a[k] = b[k];
}
}
Example
5 15
5 15 24
1 5 8 15 24 3 10 16 20
0 1 2 3 4 5 6 7 8
1 3 5 8 10 15 16 20 24
k = m + n elements.
Time complexity for this merging formation is Theta(m + n).
Where m denotes no. of elements in one sorted sub – list.
n denotes no. of elements in another sorted sub – list.
Finding Maximum and Minimum element using Divide and
Conquer
Conquer : In this step, each sub – problem or each sub – list is solved
recursively.
The first element is treated as low value, whereas the last element is
treated as high value. If n = 7, then high = n – 1, as we have taken
starting index as 0 in the above example. So, Low = 0; high = 6
The first step is to divide. In divide step, the given array is divided
into 2 parts. We can divide the array into 2 parts by calculating the
mid value.
mid = (0 + 6) / 2 = 6 / 2 = 3
0 1 2 3 4 5 6
7 10 13 71 32 83 2
7 10 13 71
List 1
32 83 2
List 2
List 1 ranges from low to this mid value. That is, low = 0; Mid = 3, so
it ranges from 0 to 3.
Whereas List 2 ranges from (Mid + 1) to high value. That is, Mid + 1
= 3 + 1 = 4; high = 6, so it ranges from 4 to 6.
Again, we have to solve the List 1 and List 2 recursively. Now, we
need to calculate the Mid value.
Mid = Floor [(0 + 3) / 2] = [3/2] = 1
0 1 2 3 4 5 6
7 10 13 71 32 83 2
7 10 13 71
32 83 2
7 10
13 71 32 83
0 1 2 3 4 5 6
7 10 13 71 32 83 2
7 10 13 71
32 83 2
7 10
13 71 32 83
0 1 2 3 4 5 6
7 10 13 71 32 83 2
7 10 13 71
32 83 2
7 10
Min = 7; Max = 10
13 71 32 83
Min = 13; Max = 71
Min = 32; Max = 83
2
Min = 7; Max = 71
Max = Min = 2
Min = 2; Max = 83
Now, compare 10 and 71 which one is maximum, Max = 71.
Compare 7 and 13, which one is minimum, Min = 7. Compare 83 and
2 which one is maximum, Max = 83. Compare 32 and 2 which is
minimum, Min = 2.
That’s why in Conquer step, we are solving the problem recursively
as long as the list contains 1 or 2 elements.
If there are 2 elements, then 1 element will become maximum
element and the other element will become minimum element.
Whereas if the list contains only 1 element then that element solely
will becomes both maximum and minimum.
0 1 2 3 4 5 6
7 10 13 71 32 83 2
7 10 13 71
32 83 2
7 10
Min = 7; Max = 10
13 71 32 83
Min = 13; Max = 71
Min = 32; Max = 83
2
Min = 7; Max = 71
Max = Min = 2
Min = 2; Max = 83
𝑛
List 2 contains the elements 50, 60, 70, 80 and it is 𝑇 ( ).
2
𝑛
= 2 [2𝑇 ( ) + 2] + 2.
4
𝑛
= 4𝑇 ( ) + 4 + 2.
4
𝑛
= 4 (2𝑇 ( ) + 2] + 4 + 2.
8
𝑛
= 8𝑇 ( ) + 8 + 4 + 2
8
𝑛
= 23 𝑇 ( 3 ) + 2 3 + 22 + 21
2
𝑛
= 22𝑇 ( 2 ) + 22 + 21
2
. . .
𝑛
T(n) = 2 k - 1𝑇 ( )+ ∑𝑘−1
𝑖=1 2
𝑖
2𝑘−1
m–n m–n 𝑎𝑚
This is in the form of a . So, a =
𝑎𝑛
2𝑘 2𝑛
T(n) = ( ) 𝑇 ( 𝑘 ) + ∑𝑘−1
𝑖=1 2
𝑖
2 2
Let 2k = n
𝑛 2𝑛
T(n) = 𝑇 ( ) + ∑𝑘−1
𝑖=1 2
𝑖
2 𝑛
∑𝑘−1 𝑖
𝑖=1 2 is nothing but Geometrical Progression.
𝑛 2𝑛
T(n) = 𝑇 ( ) + 2k – 2
2 𝑛
𝑛 2𝑛
= 𝑇( ) + n– 2
2 𝑛
𝑛
= 𝑇(2) + n – 2
2
𝑛
= +𝑛 −2
2
3𝑛
= −2
2
3𝑛
This is the Time Complexity is −2
2
This index 0 is sorted sub – array and unsorted sub – array is from
index 1 to 5.
Next step, from the unsorted sub – array find the minimum element.
So, the minimum element is 3 and swap this minimum element 3 with
the element which is at the beginning of the unsorted sub – array.
Pass 2:
0 1 2 3 4 5
1 3 10 8 4 7
𝑐11 𝑐12
C=[ ]
𝑐21 𝑐22
What is the work done for combining? This addition, I said that those
are not normal scalar value additions, those are matrix additions.
How much time it will take for adding two matrices?
Each element should be added with the corresponding element, so
there are n2 elements.
Time taken for adding is n2.
So, the time for combining is n2 .
1 𝑛≤2
𝑇(𝑛) = { 𝑛 2 n>2
8𝑇 ( ) + 𝑛
2
Log2 7 = 2.81 ; k = 2
Strassen has reduce the Time Complexity and the Time Complexity
will be O(n2.81) that is a little lesser than O(n3).
Weight = 15 ; n = 7
In the above problem we have 7 objects, with their Profits and
Weights. Total Weight, W = 15 kgs. Total objects n = 7.
We can assume that, we have one bag having weight 15 kgs or one
container having capacity 15 kgs.
Now, you have to select item such that you will get the maximum
profit. We cannot select all the items , because if you total the weight
of all the items then it would be greater than 15.
There are 3 approaches that we select the items where you will get the
maximum profit.
1. We can select the item first which is having maximum profit.
In the above problem, the maximum profit is 15, so that we can select
the item, then we will select 10 and so on.
2. We will select items having maximum weight, so that we can
select more and more items.
3. May be I can say that I will find out the ratio of profit by weight
and then I will select the items having maximum profit by
weight ratio as well.
In the above problem, the profit of item 3 is 15 you can say maximum
profit, but this profit is for 5 kgs, it is not for 1 kg. If you find out the
15
profit for 1kg, then profit would be = 3. So, for 1 kg it is 3.
5
So, the best approach is to find out the ratio profit by weight and then
select the item which is having the maximum profit by weight ratio.
Now, we will see all the three approaches and then we will compare
all the three approaches.
1. Select the item according to the maximum profit.
2. According to the minimum weight.
3. According to the maximum profit by weight ratio.
Approach 1: Select the items according to the maximum profit.
Total weight is 15 kgs.
Objects Profit [P] Weight [W] Remaining
Weight
3 15 5 15 – 5 = 10
2 10 3 10 – 3 = 7
6 9 3 7–3=4
5 8 1 4–1=3
4 3
7X =
21
= 3 3–3=0
4 4
5.25
Total Profit = 47.25
Now, check out which item is having maximum profit which is 15 in
this case. Then Object is 3; Profit = 15; Weight = 5; Remaining
Weight = 15 – 5 =10.
Next, maximum profit Object = 2; Profit = 10; Weight = 3;
Remaining Weight = 10 – 3 = 7.
Next, maximum profit Object = 6; Profit = 9; Weight = 3; Remaining
Weight = 7 – 3 = 4.
0 1 2 3
0 to 1 means first slot.
1 to 2 means second slot.
2 to 3 means third slot.
In the example, the first job deadline is 2. So, here we can assign
either 0 to 1 slot or 1 to 2 slot. It is our choice.
Here the formula is [r-1, r]. r is nothing but the deadline.
[2 – 1, 2] = [1, 2]
So, we need to assign the slot [1, 2] . Now, slot [1, 2] is free, so we
place J1 in that slot.
Now, assigned slots are [1, 2] as well as [2, 3] . So, two slots are
already allocated.
Next, highest profit is 38 which is the profit of the third job. So, the
next job is J3. Which slot should be allocated?
Here the formula is [r – 1, r] = [2 – 1, 2] = [1, 2].
So, we have to allocate [1, 2] but it is already occupied. Then we have
to use the formula [r – 2, r – 1] = [2 – 2, 2 – 1] = [0, 1] or we can
directly assign [0, 1] or [1, 2]. As slot [1, 2] is already occupied so we
have to assign the slot [0, 1] to the corresponding job. So, J3 should
be allocated to [0, 1] slot.
Assigned Slot Job Selected Action Profit
None J1 [1, 2] 100
[1, 2] J5 [2, 3] 152
[1, 2], [2, 3] J3 [0, 1] 190
Next, job profit is 27, which is the profit of the fourth job. So, the
deadline of J4 is 1. 1 means we have to assign [0, 1] but slot [0, 1] is
completely occupied. Here, the ‘Action’ is ‘Reject’, as we can’t place
the corresponding job in the corresponding slot. Before slot [0, 1] we
don’t have any other slot. Profit is 190 only.
Assigned Slot Job Selected Action Profit
None J1 [1, 2] 100
[1, 2] J5 [2, 3] 152
[1, 2], [2, 3] J3 [0, 1] 190
[0, 1], [1, 2], J4 Reject 190
[2, 3]
The last job is J2 and the profit is 19. So, here the assigned slots are
[0, 1], [1, 2], [2, 3]. Deadline of job J2 is 1, so, 1 means we can
allocate to [0, 1] slot, but [0, 1] slot is already allocated for J3.
Assigned Slot Job Selected Action Profit
None J1 [1, 2] 100
[1, 2] J5 [2, 3] 152
[1, 2], [2, 3] J3 [0, 1] 190
[0, 1], [1, 2], J4 Reject 190
[2, 3]
[0, 1], [1, 2], J2 Reject 190
[2, 3]
We can access this 1 directly, that is we can retrieve the first record
length directly. We can access the second program only after
accessing the first program. That is 1 + (1 +10). Next, we can retrieve
the third program only after retrieving the first two programs. That is
1 + (1 + 10) + (1 + 10 + 45). Next, we can retrieve the last program,
only after retrieving the first three programs.
That is, 1 + (1 + 10) + (1 + 10 + 45) + (1 + 10 + 45 + 70) = 194.
Total retrieval time is calculated by adding the Retrieval time of Tape
0, Retrieval time of Tape 1, Retrieval time of Tape 2.
Total Retrieval Time = 194 + 103 + 134 = 431
Means Retrieval Time, means Average Retrieval Time is 431 / 3 =
143.67
Minimum Cost Spanning Trees
Spanning Tree : A Spanning Tree is a sub – graph of a given graph.
A Spanning Tree must satisfy these 3 properties.
1. It should contain all the vertices of the graph.
Suppose if a graph contains 5 vertices, then the Spanning Tree
should contain 5 vertices. If the graph contains 3 vertices, then the
Spanning Tree should contain 3 vertices.
2. If the graph contains n vertices then the Spanning Tree should
contain n – 1 edges.
3. Spanning Tree should not contain any cycle.
Graph can be represented G(V, E), that means this Graph G contains
n number of vertices and n number of edges.
Example: The following is a graph, which contains 5 vertices and 4
edges.
2 5
3 4
G’ is the Spanning Tree for the above graph, that Spanning Tree
would contain G’(V’, E’).
V’ Number of Vertices
E’ Number of Edges
in that Spanning Tree.
What is the relation between V’ and V as well as E’ and E?
Mathematically, we can write V’ = V. That means, in a Spanning Tree
of a given graph, all the vertices in that Spanning Tree would be same
as in that graph.
V’ would be same as V. There is a difference in number of edges.
Number of edges E’ in a Spanning Tree would be subset of the
number of edges in this original graph. We can write E’ ⸦ E or
E = |V| - 1
Number of edges in a Spanning Tree would be number of Vertices in
a graph minus 1 always.
Spanning Tree would contain same number of vertices of the graph.
Number of edges in a Spanning Tree would be |V| - 1 [Number of
Vertices in the graph minus 1].
Suppose this is a graph
2 5
3 4
You are supposed to construct or draw a Spanning Tree for the graph.
A graph can have more than one Spanning Trees.
Spanning Tree contains same number of vertices as graph. It looks
like this.
Many Spanning Trees can be drawn from the above graph.
2 5
3 4
2 5
3 4
1
2 5
3 4
2 5
3 4
1
1 3
2 5
4 2
3 4
5
Suppose this graph is having some edge weights. Now, out of the
above Spanning Trees, the Spanning Tree whose total of these edge
weights is minimum. That would be the Minimum Spanning Tree
[MST].
Let us suppose, we have constructed the following Spanning Tree.
1
1
2 5
4 12 2
3 4
5
1
3
2 5
4 14 2
3 4
5
Total edge weight of this Spanning Tree is 3 + 2 + 5 + 4 = 14.
1
1 3
2 5
11 2
3 4
5
Total edge weight of the Spanning Tree is 1 + 3 + 2 + 5 = 11.
1
1 3
2 5
4 10 2
3 4
1
1
2 5
4 2
3 4
1
1 3
2 5
4 2
3 4
5
This is also not Spanning Tree, as this Spanning Tree contains a
cycle.
So, Spanning Tree should not contain a cycle and the Spanning Tree
should not be disconnected.
Properties of Spanning Tree
Removing an edge from the Spanning Tree will make it disconnected.
Adding one edge to the Spanning Tree will create a loop.
If each edge has distinct weight then there will be only one and
unique MST.
– 2
A complete undirected graph can have nn number of Spanning
Trees.
Every connected and undirected graph has at least one Spanning Tree.
Disconnected graph does not have Spanning Tree.
From a complete graph by removing max(e – n + 1) edges we can
construct a Spanning Tree.
Example :
8 2
C E
3
No need to check its cost, although it is having edge cost or weight 1
that is minimum, but that doesn’t matter. You have to remove that
loop.
Next, is remove parallel edges. In the above graph, from vertex B to
vertex D we have two edges which are parallel. So, these type of
edges are known as parallel edges.
How many ever parallel edges we have in this graph, we have to
remove those edges. In this graph, we have only one parallel edge.
Which edge has to be removed? Check out the edge weight one is 6
and another is 8.
You’re supposed to keep that edge which is having minimum weight
or cost. Since, 6 is minimum we will retain it as it is and we will
remove the edge weight 8.
7 B 6 D 5
A 3 4 2 F
8 2
C E
3
All the loops and parallel edges are removed.
Next, choose any arbitrary vertex as a root node. Suppose, if you
choose A as the root node, check out all the outgoing edges from
vertex A or incident edges from vertex A.
Two edges are there, one is with edge weight 7 and another is with
edge weight 8. You have to choose one edge that is minimum weight.
So, out of edge weights 7 and 8, we will choose this edge weight 7,
and this will go up to vertex B.
B
7
A
We have reached to vertex B, you have to choose all the outgoing
edges or you can say the incident edges from vertex B as well as from
vertex A.
It is not like that , since we have reached to vertex B we will be
checking edges only from vertex B.
There are 2 outgoing edges from vertex B and the edge weight is 3
and 6. But, still we are having one more edge with edge weight 8, we
have to compare this edge weight 8 also.
Out of 8, 3, 6 which one is having minimum edge weight? 3 is the
minimum edge weight, so we will choose this 3 which is going from
vertex B to vertex C.
B
7
A 3
C
B
7
A
3
C E
3
Check out all the outgoing edges from vertex E , vertex C, vertex B,
vertex A. From vertex E, what are the incident edges? One is from
vertex E to vertex F with edge weight 2, vertex E to vertex D with
edge weight 2, from vertex C, we are having one edge weight 4.
From vertex B, we are having one incident edge with edge weight 6.
From vertex A we are having one incident edge with edge weight 8.
Out of edge weights 8, 6, 2, 2, 4 which is having minimum weight ?
Minimum weight is 2 and 2, so we can choose any one of the edge
weight. Suppose, you have chosen this vertex F, then minimum
Spanning Tree would be
B
7 F
A 3 2
C E
3
We have one another vertex, that is vertex F.
Still one vertex is left, that is vertex D in the graph. Now, choose the
vertex with minimum edge weight ? From vertex F, we have only one
outgoing edge left that is edge weight 5.
It’s not like that we have reached vertex F, just choose it and draw the
minimum Spanning Tree.
From vertex E, incident edges are 2, 3, 2. Edge weight 2 has been
chosen, edge weight 3 has been chosen, so one edge weight 2 has
been left.
That is, from vertex C we have this edge weight 4, from vertex B one
is left that is edge weight 6, from vertex A one edge weight is 8.
out of 8, 6, 4, 2, 5 which edge is having minimum edge weight? That
is, 2 is the minimum edge weight from vertex E to vertex D.
B D
7 2 F
A 3 2
C E
3
This is the minimum Spanning Tree [MST] for the above given graph,
using Prim’s algorithm.
If you want to verify, minimum Spanning Tree [MST] or Spanning
Tree of any graph would contain the same number of vertices as that
graph contains.
There are 6 vertices in the graph and Spanning Tree also contains 6
vertices. The edges would be the subset of that edges that the graph
contains.
G(V, E) and G(V’, E’)
V = V’ and E’ ⸦ E
E’ should contain |V| - 1, where V means number of vertices in the
graph, so, E’ = |V| - 1 = 6 – 1 = 5.
So, there are 5 edges in the Spanning Tree that was constructed.
One more condition of Minimum Spanning Tree [MST] that total
edge weight of these edges should be minimum.
A graph can have more than one Spanning Tree.
Algorithm
Algorithm Prim(E, cost, n, t)
// E is the set of edges in G. cost[1:n, 1:n] is the cost adjacency matrix
// of an n vertex such that cost[i, j] is either a positive number or
//infinity if no edge(i, j) exists
//A minimum Spanning Tree is computed and stored as a set of edges
// in the array t[1 : n -1, 1:2], (t[i, 1], t[i, 2]) is an edge in the minimum
// cost spanning tree. The find cost is returned.
{
Let (k, l) be an edge of minimum cost in E;
mincost := cost[k, l];
t[l, 1] := k;
t[1, 2] := l;
for i := 1 to n do // initialize near
if (cost[i, l] < cost [i, k]) then near[i] := l;
else near[i] := k;
near[k] := near[l] := 0;
for i := 2 to n -1 do
{
//find n – 2 additional edges for t
Let j be an index such that near[j] not equal to 0 and
cost[j, near[j]] is minimum;
t[i, 1] : = j;
t[i, 2] : = near[j];
mincost = mincost + cost[j, near[j]];
near[j] := 0;
for k := 1 to n do // update near[]
if (near[k] != 0) and (cost[k, near[k]] > cost[k, j])) then
near[k] := j;
}
return mincost;
}
Kruskal’s Algorithm
The following is the graph:
10
7 A 5 B 4
F 3 6 2 E
8 2
C D
3
First step is to remove all the loops and parallel edges from the above
graph. Parallel edges means from one vertex to another vertex, two
edges are there in parallel.
In the above graph, from vertex A to vertex B one edge is having edge
weight 5 and another edge is having edge weight 10. Since, we have 2
edges, these are known as parallel edges. We’re supposed to remove
any of these edges.
Loops means an edge that is created to the same vertex, that means
both source vertex and destination vertex are same. For parallel edge,
you’ll keep that edge having minimum weight.
From edge weights 5 and 10, which edge weight is minimum?5 is the
minimum edge weight. So, you’ll remove the edge with edge weight
10.
7 A 5 B 4
F 3 6 2 E
8 2
C D
3
In Kruskal’s algorithm, you’ll arrange all the edges according to their
edge weights, all are arranged in increasing order of their edge
weights.
Out of all edge weights we are having 2 and 2 as the minimum edge
weight.
BD = 2; DE = 2 . In any order you can write, either DE or BD.
Next, minimum edge weight is 3 and for edge weight 3 is also
containing 2 edges AC = 3; CD = 3.
Next, BE = 4; AB = 5; BC = 6; AF = 7; FC = 8; BD = 2; DE = 2; AC
= 3; CD = 3; BE = 4; AB = 5; BC = 6; AF = 7; FC = 8
In the next step, you will choose minimum edge weight from the
above set.
B
2
B
2 E
D 2
A B
3 2 E
C D 2
A B
3 2 E
C D 2
3
7 B
A
3 2 E
F
C D 2
3
Next is FC, we cannot connect FC as it will form a cycle.
If the given graph is having n number of vertices then MST must
contain same number of vertices.
Suppose, there are n number of vertices, then Minimum Spanning
Tree [MST] will contain n vertices and (n – 1) edges.
Minimum Spanning Tree would contain 6 vertices, but you will be
having 6 – 1 = 5 edges.
In MST, the total cost of this tree would be minimum.
Early form of MST algorithm due to Kruskal
t := 0;
while ((t has less than n – 1 edges) and (E != 0)) do
{
choose an edge (v, w) from E of lowest cost;
Delete (v, w) from E;
If (v, w) does not create a cycle in t then add (v, w) to t;
else
discard(v, w);
}
Kruskal’s Algorithm
Algorithm Kruskal(E, cost, n, t)
// E is the set of edges in G. G has n vertices
//cost[u, v] is the cost of edge (u, v)
//t is the set of edges in MST. The final cost is returned.
{
Construct a heap out of the edge costs using heapify;
for i := 1 to n do
parent [i] := -1;
//Each vertex is in a different set
i := 0; mincost := 0.0;
while ((i<n -1) and (heap not empty)) do
{
Delete a minimum cost edge (u, v) from the heap and heapify
using Adjust;
j := find(u); k := find(v);
if (j != k) then
{
i := i + 1;
t[i, 1] := u; t[i, 2] := v;
mincost := mincost + cost[u, v];
union(j, k);
}
}
if (i != (n – 1)) then write (“No Spanning Tree”);
else
return mincost;
}
Dijkstra’s Algorithm
Single Source Shortest Path Problem
8 7 9
1 2 3
4 11 2 4 14
7
0
8
4
8 7 6 10
5 6
1 2
In this algorithm one source is given we’re supposed to find out the
shortest path may be and you’re supposed consider 0 as a source
vertex and from 0 we are supposed to find out the shortest path to all
the vertices.
May be you’re supposed to vertex 2 as the source vertex and we are
supposed to find out the shortest path from 2 to 1, 2 to 4, 2 to 8, 2 to
5, 2 to 6 and so on to all other vertices.
From one source we are supposed to find out the shortest path to all
other vertices.
Working Principle of Dijkstra’s Algorithm
8 7 9
1 2 3
4 11 2 4 14
7
0
8
8 7 6 10
4 5 6
1 2
Suppose the graph is given above and we’re supposed to find out the
shortest path and source vertex that is given to is 0.
Or
May be we can consider 5 as a source vertex and start the algorithm.
But for now we’re considering vertex 0 as source.
Distance of source vertex to source vertex is 0. The distance of all
other vertices would be infinity and is represented as I that is we don’t
know what is the shortest path .
I 8 I 7 I 9
1 2 3
4 11 2 4 14 I
7
0 0 8 I
8 7 6 10
4 5 6
I 1 I 2 I
I Infinity
From 0 to how many vertices are directly connected. We can find out
the distance from vertex 0 to vertex 1 and from vertex 0 to vertex 4.
How the distance is calculated?
Suppose we are considering from 0 to 1, now we need to calculate
this distance. We will consider vertex 0 as u and vertex 1 as v.
As we need to find out the distance from vertex 0 to vertex 1 . At the
beginning we don’t know the distance of v, hence d(v) is infinity (I).
We will update the infinity value and replace it with the newly
calculated value.
d(u) + c(u, v) < d(v)
0+4<I=4<I
Suppose we are considering from 0 to 4, now we need to calculate
this distance. We will consider vertex 0 as u and vertex 4 as v.
0+8<I=8<I
If (d(u) + c(u, v) < d(v))
d(v) = d(u) + c(u, v)
4 8 12 7 I 9
1 2 3
4 11 2 4 14 I
7
0 0 8 I
8 7 6 10
4 5 6
8 1 I 2 I
4 8 12 7 I 9
1 2 3
8
4 11 2 4 14 I
7
0 0 15
8 7 6 10
5 6
8 1 9 2 I
4 8 12 7 I 9
1 2 3
4 11 2 4 14 I
7
0 0 8 15
8 7 6 10
4 5 6
8 1 9 2 11
4 8 12 7 I 9
1 2 3
4 11 2 4 14 21
7
0 0 8 15
8 7 6 10
4 5 6
8 1 9 2 11
4 8 12 7 25 9
1 2 3
4 11 2 4 14 21
7
0 0 8 15
8 7 6 10
4 5 6
8 1 9 2 11
4 8 12 7 25 9
1 2 3
4 11 2 4 14 21
7
0 0 8 14
8 7 6 10
4 5 6
8 1 9 2 11
Find out the distance from vertex 2 to vertex 3? 12 + 7 < 25 ; 19 < 25.
We will update 19 with 25.
4 8 12 7 19 9
1 2 3
4 11 2 4 14 21
7
0 0 8 14
8 7 6 10
4 5 6
8 1 9 2 11
Let us see the above graph, which one is directed and weighted. We
are supposed to find out the shortest distance from the source vertex
to all other vertices.
Let us suppose A is the source vertex. In the case of a directed graph,
we will update in table.
In tabular format, the source vertex must be written at the beginning
only. Here, we have considered source vertex as A.
A B C D E
A 0 I I I I
10
Distance of source vertex to source vertex is 0. For all the remaining
vertices it would be infinity [I]. Out of the distances that are listed in
tabular format which one is having the minimum distance factor. 0 is
the minimum distance factor.
So, we will select this 0 and the vertex is A.
From, vertex A to how many vertices you can find out the distance.
That is, from vertex A to vertex B and vertex A to vertex C. There is
no edge from vertex A to vertex E. The edge that is shown in the
graph will be from vertex E to vertex A. So, we cannot update from
vertex A to vertex E. We can update only from vertex A to vertex B
and vertex A to vertex C.
Find out distance from vertex A to vertex B?
Distance of A is 0.
Formula is :
If (d(u) + cost(u, v) < d(v)) then
d(v) = d(u) + cost(u, v)
0 + 10 < I ; 10 < I . We will update the table at vertex B, the distance
is 10.
0 + 5 < I; 5 < I, we, will update the table at vertex C, the distance is 5.
A B C D E
A 0 I I I I
C 10 5 I I
Since, vertex A is already selected, we will not update this in the
table.
Out of the vertices B, C, D, E which one is having the shortest
distance factor?
The minimum distance factor is 5 which is at vertex C, so, vertex C is
selected.
From vertex C we can update distance of vertex C to vertex B and
vertex C to vertex D and vertex C to vertex E.
Now, find out the distance from vertex C to vertex B?
5 + 3 < 10 ; 8 < 10; we will update the distance of vertex B which is
8.
Next, from vertex C to vertex D. 5 + 9 < I ; 14 < I. We can update the
distance of D that is 14.
Next, from vertex C to vertex E. 5 + 2 < I; 7 < I . We can update the
distance of E, that is 7.
We will not write this vertex C value 5 again, because we have
already selected vertex C.
A B C D E
A 0 I I I I
C 10 5 I I
E 8 14 7
Now, we have only two vertices which are unvisited. Out of these two
vertices B and D which one is having minimum distance? We will
select this 8 which is the distance factor of vertex B. Vertex B would
be selected.
Then, from vertex B we can update only the distance from vertex B to
vertex D. 8 + 1 < 13; 9 < 13, then we will update the distance at
vertex D.
A B C D E
A 0 I I I I
C 10 5 I I
E 8 14 7
B 8 13
D 9