1.1 Concept of Algorithm
1.1 Concept of Algorithm
Rajat jain
ADA
If one goes through these 6 steps without being aware of the statement
of the problem, he could possibly feel that this is the algorithm for
cleaning a toilet. This is because of several ambiguities while
comprehending every step. The step 1 may imply tooth brush, paint
brush, toilet brush etc. Such an ambiguity doesn’t an instruction an
algorithmic step. Thus every step should be made unambiguous. An
unambiguous step is called definite instruction. Even if the step 2 is
rewritten as apply the tooth paste, to eliminate ambiguities yet the
conflicts such as, where to apply the tooth paste and where is the source
of the tooth paste, need to be resolved. Hence, the act of applying the
toothpaste is not mentioned. Although unambiguous, such unrealizable
steps can’t be included as algorithmic instruction as they are not effective.
The definiteness and effectiveness of an instruction implies the successful
termination of that instruction. However the above two may not be
sufficient to guarantee the termination of the algorithm. Therefore, while
designing an algorithm care should be taken to provide a proper
termination for algorithm.
Thus, every algorithm should have the following five characteristic feature
1. Input
2. Output
3. Definiteness
4. Effectiveness
5. Termination
Example 1:
Problem : finding the largest value among n>=1 numbers.
Input : the value of n and n numbers
Output : the largest value
Steps :
1. Let the value of the first be the largest value denoted by BIG
2. Let R denote the number of remaining numbers. R=n-1
3. If R != 0 then it is implied that the list is still not exhausted.
Therefore look the next number called NEW.
4. Now R becomes R-1
5. If NEW is greater than BIG then replace BIG by the value of
NEW
6. Repeat steps 3 to 5 until R becomes zero.
7. Print BIG
8. Stop
End of algorithm
Example 2: quadratic equation
Example 3: listing all prime numbers between two limits n1 and n2.
1.2.1 Algorithmic Notations
In this section we present the pseudocode that we use through out the
book to describe algorithms. The pseudo code used resembles PASCAL
and C language control structures. Hence, it is expected that the reader
be aware of PASCAL/C. Even otherwise atleast now it is required that the
reader should know preferably C to practically test the algorithm in this
course work.
However, for the sake of completion we present the commonly employed
control constructs present in the algorithms.
If < condition> then
Block 1
Else
Block 2
If end.
This pseudocode executes block1 if the condition is true otherwise
block2 is executed.
2. The two types of loop structures are counter based and conditional
based and they are as follows
Block
For end
Rajat jain
ADA
Here the block is executed for all the values of the variable from value 1
to value 2.
While (condition) do
Block
While end.
Here block gets executed as long as the condition is true.
o Repeat
Block
Until<condition>
Here block is executed as long as condition is false. It may be observed
that the block is executed atleast once in repeat type.
Exercise 1;
Devise the algorithm for the following and verify whether they satisfy all
the features.
If there are more then one possible way of solving a problem, then one
may think of more than one algorithm for the same problem. Hence, it
is necessary to know in what domains these algorithms are applicable.
Data domain is an important aspect to be known in the field of
algorithms. Once we have more than one algorithm for a given problem,
how do we choose the best among them? The solution is to devise some
data sets and determine a performance profile for each of the algorithms.
A best case data set can be obtained by having all distinct data in the set.
But, it is always complex to determine a data set, which exhibits some
average behavior. The following sections give a brief idea of the well-
known accepted algorithms.
Rajat jain
ADA
Rajat jain
ADA
x1(k+1)=(b1-a12x2(k+1)-a13x3(k))/a11
x2(k+1)=(b2-a21x1(k+1)-a23x3(k))/a22
x3(k+1)=(b3-a31x1(k+1)-a32x3(k+1))/a33
for k=1,2,3,…
This process is continued upto some desired accuracy. Numerical iterative
methods are also applicable for obtaining the roots of the equation of the
form f(x)=0. The various iterative methods used for this purpose are,
2.2 Searching
Let us assume that we have a sequential file and we wish to retrieve an
element matching with key ‘k’, then, we have to search the entire file
from the beginning till the end to check whether the element matching k
is present in the file or not.
There are a number of complex searching algorithms to serve the purpose
of searching. The linear search and binary search methods
are relatively straight forward methods of searching.
Rajat jain
ADA
{
write("search successful")
write(k is at location i)
exit();
}
else
i++
if end
while end
write (search unsuccessful);
algorithm ends.
2.2.2 Binary search
Binary search method is also relatively simple method. For this method it
is necessary to have the vector in an alphabetical or numerically
increasing order. A search for aparticular item with X resembles the
search for a word in the dictionary. The approximate mid entry is located
and its key value is examined. If the mid value is greater than X, then the
list is chopped off at the (mid-1)th location. Now the list gets reduced to
half the original list. The middle entry of the left-reduced list is examined
in a similar manner. This procedure is repeated until the item is found
or the list has no more elements. On the other hand, if the mid value is
lesser than X, then the list is chopped off at (mid+1)th location. The
middle entry of the right-reduced list is examined and the procedure is
continued until desired key is found or the search interval is exhausted.
The algorithm for binary search is as follows,
Algorithm : binary search
Input : A, vector of n elements
K, search element
Output : low –index of k
Method : low=1,high=n
While(low<=high-1)
{
mid=(low+high)/2
if(k<a[mid])
high=mid
else
low=mid
if end
}
while end
if(k=A[low])
{
write("search successful")
write(k is at location low)
exit();
}
Rajat jain
ADA
else
write (search unsuccessful);
if end;
algorithm ends.
2.3 Sorting
One of the major applications in computer science is the sorting
of information in a table. Sorting algorithms arrange items in a set
according to a predefined ordering relation. The most common types of
data are string information and numerical information. The ordering
relation for numeric data simply involves arranging items in sequence
from smallest to largest and from largest to smallest, which is called
ascending and descending order respectively.
The items in a set arranged in non-decreasing order are
{7,11,13,16,16,19,23}. The items in a set arranged in descending order
is of the form {23,19,16,16,13,11,7}
Similarly for string information, {a, abacus, above, be, become,
beyond}is in ascending order and { beyond, become, be, above, abacus,
a}is in descending order.
There are numerous methods available for sorting information. But, not
even one of them is best for all applications. Performance of the methods
depends on parameters like, size of the data set, degree of relative order
already present in the data etc.
2.3.1 Selection sort
The idea in selection sort is to find the smallest value and place it in an
order, then find the next smallest and place in the right order. This
process is continued till the entire table is sorted.
Consider the unsorted array,
a[1] a[2] a[8]
20 35 18 8 14 41 3 39
One way to sort the unsorted array would be to perform the following
steps:
Rajat jain
ADA
Repeat this process until the entire array is sorted. The changes
undergone by the array is shown in fig 2.2.The number of moves with this
technique is always of the order O(n).
Initially the whole array is unordered. So select the minimum and put it in
place of a[1] to act as sentinel. Now the array is of the form,
a[1] a[2] a[8]
3 35 18 8 14 41 20 39
Now we have one element in the sorted list and the remaining elements
are in the unordered set. Select the next element to be inserted. If the
selected element is less than the preceding element move the preceding
element by one position and insert the smaller element.
In the above array the next element to be inserted is x=35, but the
preceding element is 3 which is less than x. Hence, take the next element
Rajat jain
ADA
for insertion i.e., 18. 18 is less than 35, so move 35 one position ahead
and place 18 at that place. The resulting array will be,
a[1] a[2] a[8]
3 18 35 8 14 41 20 39
Rajat jain
ADA
2.4 Recursion
Recursion may have the following definitions:
-The nested repetition of identical algorithm is recursion.
-It is a technique of defining an object/process by itself.
-Recursion is a process by which a function calls itself repeatedly until
some specified condition has been satisfied.
Rajat jain
ADA
Rajat jain
ADA
2.5 Hashing
Rajat jain
ADA
If f(x1)=f(x2), where x1and x2 are any two variables, then x1and x2 are
called synonyms. Synonyms are mapped onto the same bucket. If a new
identifier is hashed into a already complete bucket, collision occurs.
A hashing table with single slot is as given below. Let there be 26 buckets
with single slot. The identifier to be stored are GA, D, A, G, L, A2, A1, A3,
A4, Z, ZA, E. Let f(x) be the function which maps on to a address equal to
the position of the first character of the identifier in the set of English
alphabet. The hashing table generated is as shown in fig 2.7.
Time taken to retrieve the identifiers is as follows,
Search Search
element (x) time (t)
GA 1
D 1
A 1
G 2
L 1
A2 2
A1 3
A3 5
A4 6
Z 1
ZA 10
Rajat jain
ADA
E 6
∑t =39
Rajat jain
ADA
Fig 3-1.
In the Fig. 3-1 edge e1 having same vertex as both its end vertices is
called a self-loop. There may be more than one edge associated with a
given pair of vertices, for example e4 and e5 in Fig. 3-1. Such edges are
referred to as parallel edges.
A graph that has neither self-loop nor parallel edges are called a simple
graph, otherwise it is called general graph. It should also be noted that,
in drawing a graph, it is immaterial whether the lines are drawn straight
or curved, long or short: what is important is the incidence between the
edges and vertices.
A graph is also called a linear complex, a 1-complex, or a one-
dimensional complex. A vertex is also referred to as a node, a junction,
a point, 0-cell, or an 0-simplex. Other terms used for an edge are
a branch, a line, an element, a 1-cell, an arc, and a 1-simplex.
Because of its inherent simplicity, graph theory has a very wide range
of applications in engineering, physical, social, and biological sciences,
linguistics, and in numerous other areas. A graph can be used to
represent almost any physical situation involving discrete objects and a
relationship among them.
3.1.2 Finite and Infinite Graphs
Although in the definition of a graph neither the vertex set V nor the
edge set E need be finite, in most of the theory and almost
all applications these sets are finite. A graph with a finite number of
vertices as well as a finite number of edges is called a finite graph;
otherwise, it is an infinite graph.
3.1.3 Incidence and Degree
When a vertex vi is an end vertex of some edge ej, vi and ej are said to
be incident with (on or to) each other. In Fig. 3-1, for example, edges e2,
e6, and e7 are incidentwith vertex v4. Two nonparallel edges are said to be
adjacent if they are incident on a common vertex. For example, e2 and
e7 in Fig. 3-1 are adjacent. Similarly, two vertices are said to be adjacent
if they are the end vertices of the same edge. In Fig. 3-1, v4 and v5 are
adjacent, but v1 and v4 are not.
The number of edges incident on a vertex vi, with self-loops counted twice
is called the degree, d(vi), of vertex vi. In Fig. 3-1, for example, d(v1) =
Rajat jain
ADA
Fig. 3-2 Graph containing isolated vertices, series edges and a pendant
vertex.
In the definition of a graph G = (V, E), it is possible for the edge set E to
be empty. Such a graph, without any edges, is called a null graph. In
other words, every vertex in a null graph is an isolated vertex. A null
graph of six vertices is shown in Fig. 3-3. Although the edge set E may be
empty, the vertex set V must not be empty; otherwise, there is no graph.
In other words, by definition, a graph must have at least one vertex.
Fig. 3-3 Null graph of six vertices.
Rajat jain
ADA
(a)
abcdefgh
v1 0 0 0 1 0 1 0 0
v2 0 0 0 0 1 1 1 1
v3 0 0 0 0 0 0 0 1
v4 1 1 1 0 1 0 0 0
v5 0 0 1 1 0 0 1 0
v6 1 1 0 0 0 0 0 0
(b)
Fig. 3-4 Graph and its incidence matrix.
Such a matrix A is called the vertex-edge incidence matrix, or
simply incidence matrix. Matrix A for a graph G is sometimes also written
as A(G). A graph and its incidence matrix are shown in Fig. 3-4. The
incidence matrix contains only two elements, 0 and 1. Such a matrix is
called a binary matrix or a (0, 1)-matrix.
The following observations about the incidence matrix A can readily be
made:
Rajat jain
ADA
3.3 Trees
The concept of a tree is probably the most important in graph theory,
especially for those interested in applications of graphs.
A tree is a connected graph without any circuits. The graph in Fig 3-5 for
instance, is a tree. It follows immediately from the definition that a tree
has to be a simple graph, that is, having neither a self-loop nor parallel
edges (because they both form circuits).
3.3.1 Some properties of Trees
1. There is one and only one path between every pair of vertices in a
tree, T.
2. A tree with n vertices has n-1 edges.
3. Any connected graph with n vertices and n-1 edges is a tree.
4. A graph is a tree if and only if it is minimally connected.
Rajat jain
ADA
considered the root of the tree, and so the tree is rooted. Generally, the
term tree means trees without any root. However, for emphasis they are
sometimes called free trees (or non rooted trees) to differentiate them
from the rooted kind.
Fig. 3-6 Tree.
Binary Trees: A special class of rooted trees, called binary rooted trees, is
of particular interest, since they are extensively used in the study of
computer search methods, binary identification problems, and variable-
length binary codes. A binary tree is defined as a tree in which there is
exactly one vertex of degree two, and each of the remaining vertices
of degree one or three. Since the vertex of degree two is distinct from all
other vertices, this vertex serves as a root. Thus every binary tree is a
rooted tree.
3.3.4 Spanning Trees
So far we have discussed the trees when it occurs as a graph by itself.
Now we shall study the tree as a subgraph of another graph. A given
graph has numerous subgraphs, from e edges, 2e distinct combinations
are possible. Obviously, some of these subgrphs will be trees. Out of
these trees we are particularly interested in certain types of trees,
called spanning trees.
A tree T is said to be a spanning tree of a connected graph G if T is a
subgraph of G and T contains all vertices of G. Since the vertices of G are
barely hanging together in a spanning tree, it is a sort of skeleton of the
original graph G. This is why a spanning tree is sometimes referred to as
a skeleton or scaffolding of G. Since spanning trees are the largest trees
among all trees in G, it is also quite appropriate to call a spanning tree
a maximal tree subgraph or maximal tree of G.
Finding a spanning tree of a connected graph G is simple. If G has no
circuit, it is its own spanning tree. If G has a circuit, delete an edge
from the circuit. This will still leave the graph connected. If there are
more circuits, repeat the operation till an edge from the last circuit is
deleted, leaving a connected, circuit-free graph that contains all the
vertices of G.
3.3.5 Hamiltonian Paths and Circuits
Hamiltonian circuit in a connected graph is defined as a closed walk that
traverses every vertex of G exactly once, except of course the starting
vertex, at which the walk also terminates. A circuit in a connected graph
G is said to be Hamiltonian if it includes every vertex of G. Hence a
Hamiltonian circuit in a graph of n vertices consists of exactly n edges.
Rajat jain
ADA
1. Draw all simple graphs of one, two, three and four vertices
2. Name 10 situations that can be represented by means of
graphs. Explain what each vertex and edge represent
Rajat jain
ADA
The most widely known and often used of these is the divide and
conquer strategy.
The basic idea of divide and conquer is to divide the original problem into
two or more sub-problems which can be solved by the same technique. If
it is possible to split the problem further into smaller and smaller sub-
problems, a stage is reached where the sub-problems are small enough to
be solved without further splitting. Combining the solutions of the
individuals we get the final conquering. Combining need not mean, simply
the union of individual solutions.
Divide and Conquer involves four steps
1. Divide
2. Conquer [Initial Conquer occurred due to solving]
3. Combine
4. Conquer [Final Conquer].
Rajat jain
ADA
{
If size(P,Q) is small Then
Solve(P,Q)
Else
M divide(P,Q)
Combine (D&C(P,M), D&C(M+1,Q))
}
Sometimes, this type of algorithm is known as control abstract algorithms
as they give an abstract flow. This way of breaking down the problem has
found wide applicationin sorting, selection and searching algorithm.
4.1 Binary Search:
Algorithm:
m (p+q)/2
If (p m q) Then do the following Else Stop
If (A(m) = Key Then ‘successful’ stop
Else
If (A(m) < key Then
q=m-1;
Else
p m+1
End Algorithm.
Illustration :
Consider the data set with elements {12,18,22,32,46,52,59,62,68}. First
let us consider the simulation for successful cases.
Successful cases:
Key=12 P Q m Search
195x
142x
1 1 1 successful
To search 12, 3 units of time is required
Key=18 P Q m Search
195x
1 4 2 successful
To search 18, 2 units of time is required
Key=22 P Q m Search
195x
142x
3 4 3 successful
To search 22, 3 units of time is required
Key=32 P Q m Search
195x
142x
343x
4 4 4 successful
To search 32, 4 units of time is required
Key=46 P Q m Search
Rajat jain
ADA
1 9 5 successful
To search 46, 1 unit of time is required
Key=52 P Q m Search
195x
697x
6 6 6 successful
To search 52, 3 units of time is required
Key=59 P Q m Search
195x
6 9 7 successful
To search 59, 2 units of time is required
Key=62 P Q m Search
195x
697x
8 9 8 successful
To search 62, 3 units of time is required
Key=68 P Q m Search
195x
697x
898x
9 9 9 successful
To search 68, 4 units of time is required
3+2+3+4+1+3+2+4
Successful average search time= -------------------------
9
unsuccessful cases
Key=25 P Q m Search
195x
142x
343x
444x
To search 25, 4 units of time is required
Key=65 P Q m Search
195x
697x
898x
999x
To search 65, 4 units of time is required
4+4
Unsuccessful search time =--------------------
2
average (sum of unsuccessful search time
search = + sum of Successful search time)/(n+(n+1))
Rajat jain
ADA
time
4.2 Max-Min Search
Max-Min search problem aims at finding the smallest as well as the
biggest element in a vector A of n elements.
Following the steps of Divide and Conquer the vector can be divided into
sub-problem as shown below.
The search has now reduced to comparison of 2 numbers. The time is
spent in conquering and comparing which is the major step in
the algorithm.
Algorithm: Max-Min (p, q, max, min)
{
If (p = q) Then
max = a(p)
min = a(q)
Else
If ( p – q-1) Then
If a(p) > a(q) Then
max = a(p)
min = a(q)
Else
max = a(q)
min = a(p)
If End
Else
m (p+q)/2
Rajat jain
ADA
max-min(p,m,max1,min1)
max-min(m+1,q,max2,min2)
max large(max1,max2)
min small(min1,min2)
If End
If End
Algorithm End.
Illustration
Consider a data set with elements {82,36,49,91,12,14,06,76,92}. Initially
the max and min variables have null values. In the first call, the list is
broken into two equal halves.. The list is again broken down into two. This
process is continued till the length of the list is either two or one.
Then the maximum and minimum values are chosen from the smallest list
and these values are returned to the preceding step where the length
of the list is slightly big. This process is continued till the entire list is
searched. The detail description is shown in fig 4.1
4.3 Integer multiplication
There are various methods of obtaining the product of two numbers. The
repeated addition method is left as an assignment for the reader. The
reader is expected to find the product of some bigger numbers using the
repeated addition method.
Another way of finding the product is the one we generally use i.e.,
the left shift method.
Rajat jain
ADA
981*1234
3924
2943*
1962**
981***
1210554
In this method, a=981 is the multiplicand and b=1234 is the multiplier. A
is multiplied by every digit of b starting from right to left. On
each multiplication the subsequent products are shifted one place left.
Finally the products obtained by multiplying a by each digit of b is
summed up to obtain the final product.
The above product can also be obtained by a right shift method, which
can be illustrated as follows,
4.3.2 right shift method
981*1234
981
1962
*2943
**3924
1210554
In the above method, a is multiplied by each digit of b from leftmost digit
to rightmost digit. On every multiplication the product is shifted one place
to the right and finally all the products obtained by multiplying ‘a’ by each
digit of ‘b’ is added to obtain the final result.
The product of two numbers can also be obtained by dividing ‘a’
and multiplying ‘b’ by 2 repeatedly until a<=1.
4.3.3 halving and doubling method
Let a=981 and b=1234
The steps to be followed are
1. If a is odd store b
2. A=a/2 and b=b*2
3. Repeat step 2 and step 1 till a<=1
a b result
Rajat jain
ADA
61 19744 19744
30 39488 ------------
15 78976 78976
7 157952 157952
3 315904 315904
1 631808 631808
Sum=1210554
The above method is called the halving and doubling method.
4.3.4 Speed up algorithm:
In this method we split the number till it is easier to multiply. i.e., we split
0981 into 09 and 81 and 1234 into 12 and 34. 09 is then multiplied by
both 12 and 34 but, the products are shifted ‘n’ places left before adding.
The number of shifts ‘n’ is decided as follows
Multiplicationsequence shifts
09*12 4 108****
09*34 2 306**
81*12 2 972**
81*34 0 2754
Sum=1210554
For 0981*1234, multiplication of 34 and 81 takes zero shifts, 34*09 takes
2 shifts, 12 and 81 takes 2 shifts and so on.
Exercise 4
1. Write the algorithm to find the product of two numbers for all the
methods explained.
2. Hand simulate the algorithm for atleast 10 different numbers.
3. Implement the same for verification.
4. Write a program to find the maximum and minimum of the list of n
element with and without using recursion.
Rajat jain
ADA
Rajat jain
ADA
Illustration
Consider a knapsack problem of finding the optimal solution where,
M=15, (p1,p2,p3…p7) = (10, 5, 15, 7, 6, 18, 3) and (w1, w2, …., w7) =
(2, 3, 5, 7, 1, 4, 1).
In order to find the solution, one can follow three different srategies.
Strategy 1 : non-increasing profit values
Let (a,b,c,d,e,f,g) represent the items with profit (10,5,15,7,6,18,3) then
the sequence of objects with non-increasing profit is (f,c,a,d,e,b,g).
Item chosen Quantity of item Remaining PiXi
for inclusion included space in M
Profit= 47 units
The solution set is (1,0,1,4/7,0,1,0).
Strategy 2: non-decreasing weights
The sequence of objects with non-decreasing weights is (e,g,a,b,f,c,d).
Item chosen Quantity of item Remaining PiXI
Rajat jain
ADA
Profit= 54 units
The solution set is (1,1,4/5,0,1,1,1).
Strategy 2: maximum profit per unit of capacity used
(This means that the objects are considered in decreasing order of the ratio Pi/wI)
g: P7/w7 =3/1=3
The solution set is (1,2/3,1,0,1,1,1).
In the above problem it can be observed that, if the sum of all the
weights is M then all xi = 1, is an optimal solution. If we assume that
the sum of all weights exceeds M, all xi’s cannot be one. Sometimes it
becomes necessary to take a fraction of some items to completely fill the
knapsack. This type of knapsack problems is a general knapsack problem.
Rajat jain
ADA
Illustration:
Consider 5 jobs with profits (p1,p2,p3,p4,p5) = (20,15,10,5,1) and
maximum delay allowed (d1,d2,d3,d4,d5) = (2,2,1,3,3).
Here maximum number of jobs that can be completed is =
Min(n,maxdelay(di))
= Min(5,3)
= 3.
Hence there is a possibility of doing 3 jobs.
There are 3 units of time
Time Slot
[0-1] [1-2] [2-3] Profit
Job
1 - yes - 20
2 yes - - 15
3 cannot accommodate --
4 - - yes 5
Rajat jain
ADA
40
In the first unit of time job 2 is done and a profit of 15 is gained, in the
second unit job 1 is done and a profit 20 is obtained finally in the 3 rd unit
since the third job is not available 4th job is done and 5 is obtained as the
profit in the above job 3 and 5 could not be accommodated due to their
deadlines.
Exercise 5
6.1 Backtracking
Problems, which deal with searching a set of solutions, or which ask for
an optimal solution satisfying some constraints can be solved using the
backtracking formulation. The backtracking algorithm yields the
proper solution in fewer trials.
The basic idea of backtracking is to build up a vector one component at a
time and to test whether the vector being formed has any chance of
success. The major advantage of this algorithm is that if it is realized that
the partial vector generated does not lead to an optimal solution then that
vector may be ignored.
Backtracking algorithm determine the solution by systematically
searching the solution space for the given problem. This search is
accomplished by using a free organization. Backtracking is a depth first
search with some bounding function. All solutions using backtracking are
required to satisfy a complex set of constraints. The constraints may be
explicit or implicit.
Explicit constraints are rules, which restrict each vector element to be
chosen from the given set. Implicit constraints are rules, which determine
which of the tuples in the solution space, actually satisfy the criterion
function.
Rajat jain
ADA
Rajat jain
ADA
Rajat jain
ADA
The branch and bound tree for the records of length (5,10,3) is as shown
in fig 6.4
Rajat jain
ADA
Example:
Consider the digraph of fig 7-1. Let the numbers on the
edges be the costs of travelling along that route. If a person is
interested travel from v1 to v2, then he encounters many
paths. Some of them are
1. v1 v2 = 50 units
2. v1 v3 v4 v2 = 10+15+20=45 units
3. v1 v5 v4 v2 = 45+30+20= 95 units
4. v1 v3 v4 v5 v4 v2 = 10+15+35+30+20=110 units
Rajat jain
ADA
V1 - 50 10 Inf 45 Inf
Minimum 50 25 45 inf
Step 5: find the minimum in each column. Now select the minimum from
the resulting row. In the above example the minimum is 25. Repeat step
3 followed by step 4 till all vertices are covered or single column is left.
The solution for the fig 7.1 can be continued as follows
V2 V5 V6
V1 Vw 50 45 Inf
Minimum 45 45 inf
V5 V6
V1 Vw 45 Inf
Minimum 45 inf
V6
V1 Vw Inf
V1 V3 V4 V2 V5 Vw 45+inf
Minimum inf
Rajat jain
ADA
Above figure shows the complete graph on four nodes together with three
of its spanning tree.
Spanning trees have many applications. For example, they can be used
to obtain an independent set of circuit equations for an electric network.
First, a spanning tree for the electric network is obtained. Let B be the set
of network edges not in the spanning tree. Adding an edge from B to the
spanning tree creates a cycle. Kirchoff’s secondlaw is used on each cycle
to obtain a circuit equation.
Another application of spanning trees arises from the property that a
spanning tree is a minimal sub-graph G’ of G such that V(G’) = V(G) and
G’ is connected. A minimal sub-graph with n vertices must have at least
n-1 edges and all connected graphs with n-1 edges are trees. If the nodes
of G represent cities and the edges represent possible communication
links connecting two cities, then the minimum number of links needed to
connect the n cities is n-1. the spanning trees of G represent all feasible
choice.
In practical situations, the edges have weights assigned to them. Thse
weights may represent the cost of construction, the length of the link, and
so on. Given such a weighted graph, one would then wish to select cities
to have minimum total cost or minimum total length. In either case the
Rajat jain
ADA
links selected have to form a tree. If this is not so, then the selection of
links contains a cycle. Removal of any one of the links on this
cycle results in a link selection of less const connecting all cities. We are
therefore interested in finding a spanning tree of G. with minimum cost
since the identification of a minimum-cost spanning tree involves
the selection of a subset of the edges, this problem fits the subset
paradigm.
V1 V2 V3 V4 V5 V6
V1 - 10 16 11 10 17
V3 16 9.5 - 7 Inf 12
Rajat jain
ADA
V4 11 Inf 7 - 8 7
V5 10 Inf Inf 8 - 9
V6 17 19.5 12 7 9 -
Start with v1 and pick the smallest entry in row1, which is either (v1,v2)
or (v1,v5). Let us pick (v1, v5). The closest neighbor of the subgraph
(v1,v5) is v4 as it is the smallest in the rows v1 and v5. The three
remaining edges selected following the above procedure turn out to be
(v4,v6) (v4,v3) and (v3, v2) in that sequence. The resulting shortest
spanning tree is shown in fig 7.4. The weight of this tree is 41.5.
7.2.3 Kruskal’s Algorithm:
There is a second possible interpretation of the optimization criteria
mentioned earlier in which the edges of the graph are considered in non-
decreasing order of cost. This interpretation is that the set t of edges so
far selected for the spanning tree be such that it is possible to complete t
into a tree. Thus t may not be a tree at all stages in the algorithm. In
fact, it will generally only be a forest since the set of edges t can be
completed into a tree if and only if there are no cycles in t. this method is
due to kruskal.
The Kruskal algorithm can be illustrated as folows, list out all edges of
graph G in order of non-decreasing weight. Next select a smallest edge
that makes no circuit with previously selected edges. Continue this
process until (n-1) edges have been selected and these edges will
constitute the desired shortest spanning tree.
For fig 7.3 kruskal solution is as follows,
V1 to v2 =10
V1 to v3 = 16
V1 to v4 = 11
V1 to v5 = 10
V1 to v6 = 17
V2 to v3 = 9.5
V2 to v6 = 19.5
V3 to v4 = 7
V3 to v6 =12
V4 to v5 = 8
V4 to v6 = 7
Rajat jain
ADA
V5 to v6 = 9
The above path in ascending order is
V3 to v4 = 7
V4 to v6 = 7
V4 to v5 = 8
V5 to v6 = 9
V2 to v3 = 9.5
V1 to v5 = 10
V1 to v2 =10
V1 to v4 = 11
V3 to v6 =12
V1 to v3 = 16
V1 to v6 = 17
V2 to v6 = 19.5
Select the minimum, i.e., v3 to v4 connect them, now select v4 to v6 and
then v4 to v5, now if we select v5 to v6 then it forms a circuit so drop it
and go for the next. Connect v2 and v3 and finally connect v1 and v5.
Thus, we have a minimum spanning tree, which is similar to the figure
7.4.
Rajat jain
ADA
Algorithm Insert(a,n)
{
// Insert a[n] into the heap which is stored in a[1:n-1]
I=n;
item=a[n];
while( (I>n) and (a[ I!/2 ] < item)) do
{
a[I] = a[I/2];
I=I/2;
}
a[I]=item;
return (true);
}
Rajat jain
ADA
The figure shows one example of how insert would insert a new value into
an existing heap of five elements. It is clear from the algorithm and the
figure that the time for insert can vary. In the best case the new elements
are correctly positioned initially and no new values need to be rearranged.
In the worst case the number of executions of the while loop is
proportional to the number of levels in the heap. Thus if there are n
elements in the heap, inserting new elements takes O(log n) time in the
worst case.
To delete the maximum key from the max heap, we use
an algorithm called Adjust. Adjust takes as input the array a[ ] and
integer I and n. It regards a[1..n] as a complete binary tree. If the
subtrees rooted at 2I and 2I+1 are max heaps, then adjust will rearrange
elements of a[ ] such that the tree rooted at I is also a max heap. The
maximumelements from the max heap a[1..n] can be deleted by deleting
the root of the corresponding complete binary tree. The last element of
the array, i.e. a[n], is copied to the root, and finally we call Adjust(a,1,n-
1).
Algorithm Adjust(a,I,n)
{
j=2I;
item=a[I];
while (j<=n) do
{
if ((j<=n) and (a[j]< a[j+1])) then
Rajat jain
ADA
j=j+1;
//compare left and right child and let j
be the right //child
if ( item >= a[I]) then break;
// a position for item is found
a[i/2]=a[j];
j=2I;
}
a[j/2]=item;
}
Algorithm Delmac(a,n,x)
// Delete the maximum from the heap a[1..n] and store it in x
{
if (n=0) then
{
write(‘heap is empty");
return (false);
}
x=a[1];
a[1]=a[n];
Adjust(a,1,n-1);
Return(true);
}
Note that the worst case run time of adjust is also proportional to the
height of the tree. Therefore if there are n elements in the heap,
deleting the maximum can be done in O(log n) time.
To sort n elements, it suffices to make n insertions followed by n deletions
from a heap since insertion and deletion take O(log n) time each in the
worst case this sortingalgorithm has a complexity of
O(n log n).
Algorithm sort(a,n)
{
for i=1 to n do
Insert(a,i);
for i= n to 1 step –1 do
{
Delmax(a,i,x);
a[i]=x;
}
}
Rajat jain