DAA Module
DAA Module
1. REVIEW
1.1. Concept of algorithm
A common man’s belief is that a computer can do anything and everything that he
imagines. It is very difficult to make people realize that it is not really the computer but
the man behind computer who does everything.
In the modern internet world man feels that just by entering what he wants to search into
the computers he can get information as desired by him. He believes that, this is done by
computer. A common man seldom understands that a man made procedure called search
has done the entire job and the only support provided by the computer is the executional
speed and organized storage of information.
In the above instance, a designer of the information system should know what one
frequently searches for. He should make a structured organization of all those details to
store in memory of the computer. Based on the requirement, the right information is
brought out. This is accomplished through a set of instructions created by the designer of
the information system to search the right information matching the requirement of the
user. This set of instructions is termed as program. It should be evident by now that it is
not the computer, which generates automatically the program but it is the designer of the
information system who has created this.
Thus, the program is the one, which through the medium of the computer executes to
perform all the activities as desired by a user. This implies that programming a computer
is more important than the computer itself while solving a problem using a computer and
this part of programming has got to be done by the man behind the computer. Even at this
stage, one should not quickly jump to a conclusion that coding is programming. Coding is
perhaps the last stage in the process of programming. Programming involves various
activities form the stage of conceiving the problem upto the stage of creating a model to
solve the problem. The formal representation of this model as a sequence of instructions
is called an algorithm and coded algorithm in a specific computer language is called a
program.
Algorithm:
‘’a set of steps to accomplish or complete a task that is described precisely enough that a
computer can run it’’.
Described precisely: very difficult for a machine to know how much water, milk to be
added etc. in the above tea making algorithm.
These algorithms run on computers or computational devices. For example, GPS in our
smartphones, Google hangouts. GPS uses shortest path algorithm. Online shopping uses
cryptography which uses RSA algorithm.
Thus, every algorithm should have the following five characteristic features
1. Input
2. Output
3. Definiteness
4. Effectiveness
5. Termination
Therefore, an algorithm can be defined as a sequence of definite and effective
instructions, which terminates with the production of correct output from the given input.
In other words, viewed little more formally, an algorithm is a step by step formalization
of a mapping function to map input set onto an output set.
The problem of writing down the correct algorithm for the above problem of brushing the
teeth is left to the reader.
For the purpose of clarity in understanding, let us consider the following examples.
Example 1:
Problem : finding the largest value among n>=1 numbers.
Input : the value of n and n numbers
3. The two types of loop structures are counter based and conditional based and they are
as follows
While (condition) do
Block
While end.
Here block gets executed as long as the condition is true.
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.
1. An algorithm that inputs three numbers and outputs them in ascending order.
2. To test whether the three numbers represent the sides of a right angle triangle.
3. To test whether a given point p(x,y) lies on x-axis or y-axis or in I/II/III/IV quadrant.
4. To compute the area of a circle of a given circumference
5. To locate a specific word in a dictionary.
Note : it is always required to hand simulate with suitable input dataset.
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
In this method, we start to search from the beginning of the list and examine each
element till the end of the list. If the desired element is found we stop the search and
return the index of that element. If the item is not found and the list is exhausted the
search returns a zero value.
In the worst case the item is not found or the search item is the last (nth) element. For both
situations we must examine all n elements of the array so the order of magnitude or
complexity of the sequential search is n. i.e., O(n). The execution time for this algorithm
is proportional to n that is the algorithm executes in linear time.
Figure 0:3 Finding the middle index “mid” in Binary Search Algorithm
Compare the middle element of the search space with the key.
1. If the key is found at middle element, the process is terminated.
2. If the key is not found at middle element, choose which half will be used as the
next search space.
3. If the key is smaller than the middle element, then the left side is used for next
search.
4. If the key is larger than the middle element, then the right side is used for next
search.
5. This process is continued until the key is found or the total search space is
exhausted.
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
write (search unsuccessful);
if end;
algorithm ends.
Example
Consider an array arr[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91}, and the target = 23.
First Step: Calculate the mid and compare the mid element with the key. If the key is
less than mid element, move to left and if it is greater than the mid then move search
space to the right.
Key (i.e., 23) is greater than current mid element (i.e., 16). The search space moves to the
right.
Second Step: If the key matches the value of the mid element, the element is found and
stop search.
One way to sort the unsorted array would be to perform the following steps:
Find the smallest element in the unsorted array
Place the smallest element in position of a[1]
i.e., the smallest element in the unsorted array is 3 so exchange the values of a[1] and
a[7]. The array now becomes,
a[1] a[2] a[8]
3 35 18 8 14 41 20 39
Now find the smallest from a[2] to a[8] , i.e., 8 so exchange the values of a[2] and
a[4] which results with the array shown below,
a[1] a[2] a[8]
3 8 18 35 14 41 20 39
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).
School of computing and Informatics Computer Science Gutema S.
2.3.2 Insertion sort
Insertion sort is a straight forward method that is useful for small collection of data. The
idea here is to obtain the complete solution by inserting an element from the unordered
part into the partially ordered solution extending it by one element. Selecting an element
from the unordered list could be simple if the first element of that list is selected.
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,
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.
Now the element to be inserted is 8. 8 is less than 35 and 8 is also less than 18 so move
35 and 18 one position right and place 8 at a[2]. This process is carried till the sorted
array is obtained.
One of the disadvantages of the insertion sort method is the amount of movement of data.
In the worst case, the number of moves is of the order O(n2). For lengthy records it is
quite time consuming.
Problem Statement
There is a way to get all the required information with only 7 matrix multiplications,
instead of 8.
Recurrence for new algorithm is
T(n) = 7T(n/2) + O(n2)
You just need to remember 4 Rules :
AHED (Learn it as ‘Ahead’)
Diagonal
Last CR
First CR
Also, consider X as (Row +) and Y as (Column -) matrix
Recursion can be used for repetitive computations in which each action is stated in terms
of previous result. There are two conditions that must be satisfied by any recursive
procedure.
1. Each time a function calls itself it should get nearer to the solution.
2. There must be a decision criterion for stopping the process.
The recursion algorithm for finding the factorial of a number is given below,
Algorithm : factorial-recursion
Input : n, the number whose factorial is to be found.
Output : f, the factorial of n
Method : if(n=0)
f=1
else
f=factorial(n-1) * n
if end
algorithm ends.
1. Mathematical functions such as factorial and fibonacci series generation can be easily
implemented using recursion than iteration.
2. In iterative techniques looping of statement is very much necessary.
Recursion is a top down approach to problem solving. It divides the problem into pieces
or selects out one key step, postponing the rest.
Iteration is more of a bottom up approach. It begins with what is known and from this
constructs the solution step by step. The iterative function obviously uses time that is
O(n) where as recursive function has an exponential time complexity.
It is always true that recursion can be replaced by iteration and stacks. It is also true that
stack can be replaced by a recursive program with no stack.
2.5 Hashing
Consider a sequential memory shown in fig 2.6. In hashing technique the address X of a
variable x is obtained by computing an arithmetic function (hashing function) f(x). Thus
The memory used to store the variable using hashing technique is assumed to be
sequential. The memory is known as hash table. The hash table is partitioned into several
storing spaces called buckets and each bucket is divided into slots (fig 2.6).
If there are b buckets in the table, each bucket is capable of holding s variables, where
each variable occupies one slot. The function f(x) maps the possible variable onto the
integers 0 through b-1. The size of the space from where the variables are drawn is called
the identifier space. Let T be the identifier space, n be the number of variables/identifiers
in the hash table. Then, the ratio n/T is called the identifier density and a = n/sb is the
loading density or loading factor.
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
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)
School of computing and Informatics Computer Science Gutema S.
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
E 6
∑t =39
Exercise 2:
1. What are the serious short comings of the binary search method and sequential
search method.
2. Know more searching techniques involving hashing functions
3. Implement the algorithms for searching and calculate the complexities
4. Write an algorithm for the above method of selection sort and implement the
same.
A graph G = (V, E) consists of a set of objects V = {v1, v2, …} called vertices, and
another set E = {e1, e2, …} whose elements are called edges. Each edge ek in E is
identified with an unordered pair (vi, vj) of vertices. The vertices vi, vj associated with
edge ek are called the end vertices of ek. The most common representation of graph is by
means of a diagram, in which the vertices are represented as points and each edge as a
line segment joining its end vertices. Often this diagram itself is referred to as a graph.
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.
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.
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.
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 incident with
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.
A vertex having no incident edge is called an isolated vertex. In other words, isolated
vertices are vertices with zero degree. Vertex v4 and v7 in Fig. 3-2, for example, are
isolated vertices. A vertex of degree one is called a pendent vertex or an end vertex.
Vertex v3 in Fig. 3-2 is a pendant vertex. Two adjacent edges are said to be in series if
their common vertex is of degree two. In Fig. 3-2, the two edges incident on v1 are in
series.
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.
Although a pictorial representation of a graph is very convenient for a visual study, other
representations are better for computer processing. A matrix is a convenient and useful
way of representing a graph to a computer. Matrices lend themselves easily to
mechanical manipulations. Besides, many known results of matrix algebra can be readily
applied to study the structural properties of graphs from an algebraic point of view. In
many applications of graph theory, such as in electrical network analysis and operation
research, matrices also turn out to be the natural way of expressing the problem.
a b c d e f g h
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:
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).
It is observed that a tree shown in the Fig. 3-5 has several pendant vertices. A pendant
vertex was defined as a vertex of degree one). The reason is that in a tree of n vertices
we have n-1 edges, and hence 2(n-1) degrees to be divided among n vertices. Since no
vertex can be of zero degree, we must have at least two vertices of degree one in a tree.
This makes sense only if n 2.
A tree in which one vertex (called the root) is distinguished from all the others is called a
rooted tree. For instance, in Fig. 3-6 vertex named start, is distinguished from the rest of
the vertices. Hence vertex start can be 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.
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.
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.
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.
Hamiltonian path: If we remove any one edge from a Hamiltonian circuit, we are left
with a path. This path is called a Hamiltonian path. Clearly, a Hamiltonian path in a
graph G traverses every vertex of G. Since a Hamiltonian path is a subgraph of a
Hamiltonian circuit (which in turn is a subgraph of another graph), every graph that has a
Hamiltonian circuit also has a Hamiltonian path. There are, however, many graphs with
Hamiltonian paths that have no Hamiltonian circuits. The length of a Hamiltonian path
in a connected graph of n vertices is n-1.
In our problem, if each of the cities has a road to every other city, we have a complete
weighted graph. This graph has numerous Hamiltonian circuits, and we are to pick the
one that has the smallest sum of distances (or weights).
The total number of different (not edge disjoint, of course) Hamiltonian circuits in a
complete graph of n vertices can be shown to be (n-1)! / 2. This follows from the fact
that starting from any vertex we have n-1 edges to choose from the first vertex, n-2 from
the second, n-3 from the third, and so on. These being independent, results with (n-1)!
choices. This number is, however, divided by 2, because each Hamiltonian circuit has
been counted twice.
The problem is to prescribe a manageable algorithm for finding the shortest route. No
efficient algorithm for problems of arbitrary size has yet been found, although many
attempts have been made. Since this problem has applications in operations research,
some specific large-scale examples have been worked out. There are also available
several heuristic methods of solution that give a route very close to the shortest one, but
do not guarantee the shortest.
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
3. Draw a connected graph that becomes disconnected when any edge is
removed from it
4. Draw all trees of n labeled vertices for n=1,2,3,4 and 5
5. Sketch all binary trees with six pendent edges
6. Sketch all spanning trees of given graphs in this chapter
7. Write incidence matrix for all the graphs developed
8. Find the spanning trees for all the graphs developed
9. Draw a graph which has Hamiltonian path but does not have Hamiltonian
circuit
10. List different paths from vertex1 to vertex n in each graph developed.
There are a number of general and powerful computational strategies that are repeatedly
used in computer science. It is often possible to phrase any problem in terms of these
general strategies. These general strategies are Divide and Conquer, Dynamic
Programming. The techniques of Greedy Search, Backtracking and Branch and Bound
evaluation are variations of dynamic programming idea. All these strategies and
techniques are discussed in the subsequent chapters.
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.
In precise, forward journey is divide and backward journey is Conquer. A general binary
divide and conquer algorithm is :
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 application in
sorting, selection and searching algorithm.
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
pm+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=18 P Q m Search
1 9 5 x
1 4 2 successful
Key=22 P Q m Search
1 9 5 x
1 4 2 x
3 4 3 successful
Key=32 P Q m Search
1 9 5 x
1 4 2 x
3 4 3 x
4 4 4 successful
Key=46 P Q m Search
1 9 5 successful
Key=59 P Q m Search
1 9 5 x
6 9 7 successful
Key=62 P Q m Search
1 9 5 x
6 9 7 x
8 9 8 successful
Key=68 P Q m Search
1 9 5 x
6 9 7 x
8 9 8 x
9 9 9 successful
3+2+3+4+1+3+2+4
Successful average search time= -------------------------
unsuccessful cases
Key=25 P Q m Search
1 9 5 x
1 4 2 x
3 4 3 x
4 4 4 x
Key=65 P Q m Search
1 9 5 x
6 9 7 x
8 9 8 x
9 9 9 x
4+4
Unsuccessful search time =--------------------
2
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.
max large(max1,max2)
min small(min1,min2)
If End
If End
Algorithm End.
Illustration
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.
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,
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.
a b result
981 1234 1234
490 2468 ----------
--
245 4936 4936
122 9872 ---------
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.
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
Multiplication shifts
sequence
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.
GREEDY METHOD
Greedy method is a method of choosing a subset of the dataset as the solution set that
results in some profit. Consider a problem having n inputs, we are required to obtain the
solution which is a series of subsets that satisfy some constraints or conditions. Any
subset, which satisfies these constraints, is called a feasible solution. It is required to
obtain the feasible solution that maximizes or minimizes the objective function. This
feasible solution finally obtained is called optimal solution.
If one can devise an algorithm that works in stages, considering one input at a time and at
each stage, a decision is taken on whether the data chosen results with an optimal solution
or not. If the inclusion of a particular data results with an optimal solution, then the data
is added into the partial solution set. On the other hand, if the inclusion of that data
results with infeasible solution then the data is eliminated from the solution set.
Let tj be the time required retrieving program ij where programs are stored in the order
I = i1, i2, i3, …,in.
Now the problem is to store the programs on the tape so that MRT is minimized. From
the above discussion one can observe that the MRT can be minimized if the programs are
stored in an increasing order i.e., l1 l2 l3, … ln.
Hence the ordering defined minimizes the retrieval time. The solution set obtained need
not be a subset of data but may be the data set itself in a different sequence.
Illustration
Assume that 3 sorted files are given. Let the length of files A, B and C be 7, 3 and 5 units
respectively. All these three files are to be stored on to a tape S in some sequence that
reduces the average retrieval time. The table shows the retrieval time for all possible
orders.
Illustration
In order to find the solution, one can follow three different srategies.
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).
g: P7/w7 =3/1=3
In a job-scheduling problem, we are given a list of n jobs. Every job i is associated with
an integer deadline di 0 and a profit pi 0 for any job i, profit is earned if and only if
the job is completed within its deadline. A feasible solution with maximum sum of
profits is to be obtained now.
To find the optimal solution and feasibility of jobs we are required to find a subset J such
that each job of this subset can be completed by its deadline. The value of a feasible
solution J is the sum of profits of all the jobs in J.
Time Slot
[0-1] [1-2] [2-3] Profit
Job
1 - yes - 20
2 yes - - 15
3 cannot accommodate --
4 - - yes 5
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 3rd 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
1) Write the algorithm for solving cassette-filling problem on your own.
2) When one medium is not enough to store all files how do you solve it.
3) Write the algorithm to implement knapsack problem
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.
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.
In the optimal storage on tape problem, we are required to find a permutation for the n
programs so that when they are stored on the tape, the MRT is minimized.
Let n=3 and (l1,l2,l3)=(5,10,3),there are n!=6 possible orderings. These orderings and their
respective MRT is given in the fig 6.1. Hence, the best order of recording is 3,1,2.
There are n positive numbers given in a set. The desire is to find all possible subsets of
this set, the contents of which add onto a predefined value M.
The 8 queen problem can be stated as follows. Consider a chessboard of order 8X8. The
problem is to place 8 queens on this board such that no two queens are attack can attack
each other.
The term branch and bound refer to all state space search methods in which all possible
branches are derived before any other node can become the E-node. In other words the
exploration of a new node cannot begin until the current node is completely explored.
The branch and bound tree for the records of length (5,10,3) is as shown in fig 6.4
Graphs can be used to represent the highway structure of a state or country with vertices
representing cities and edges representing sections of highway. The edges can then be
assigned weights which may be either the distance between the two cities connected by
the edge or the average time to drive along that section of highway. A motorist wishing
to drive from city A to B would be interested in answers to the following questions:
The problems defined by these questions are special case of the path problem we
study in this section. The length of a path is now defined to be the sum of the
weights of the edges on that path. The starting vertex of the path is referred to as
the source and the last vertex the destination. The graphs are digraphs
representing streets. Consider a digraph G=(V,E), with the distance to be traveled
as weights on the edges. The problem is to determine the shortest path from v0 to
all the remaining vertices of G. It is assumed that all the weights associated with
the edges are positive. The shortest path between v0 and some other node v is an
ordering among a subset of the edges. Hence this problem fits the ordering
paradigm.
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) v1v3v4 v2 = 10+15+20=45 units
3) v1v5v4v2 = 45+30+20= 95 units
4) v1v3v4v5v4v2 = 10+15+35+30+20=110 units
The cheapest path among these is the path along v1v3v4v2. The cost of
the path is 10+15+20 = 45 units. Even though there are three edges on this path,
it is cheaper than travelling along the path connecting v1 and v2 directly i.e., the
path v1v2 that costs 50 units. One can also notice that, it is not possible to
travel to v6 from any other node.
Step 1: find the adjacency matrix for the given graph. The adjacency matrix for
fig 7.1 is given below
V1 V2 V3 V4 V5 V6
V1 - 50 10 Inf 45 Inf
V2 Inf - 15 Inf 10 Inf
V3 20 Inf - 15 inf Inf
V4 Inf 20 Inf - 35 Inf
V5 Inf Inf Inf 30 - Inf
V6 Inf Inf Inf 3 Inf -
Step 2: consider v1 to be the source and choose the minimum entry in the row v1.
In the above table the minimum in row v1 is 10.
Step 3: find out the column in which the minimum is present, for the above
example it is column v3. Hence, this is the node that has to be next visited.
Step 4: compute a matrix by eliminating v1 and v3 columns. Initially retain only row v1.
The second row is computed by adding 10 to all values of row v3.
The resulting matrix is
V2 V4 V5 V6
V1Vw 50 Inf 45 Inf
V1V3Vw 10+inf 10+15 10+inf 10+inf
Minimum 50 25 45 inf
V2 V5 V6
V1Vw 50 45 Inf
V1V3V4Vw 25+20 25+35 25+inf
Minimum 45 45 inf
V5 V6
V1Vw 45 Inf
V1V3V4V2V 45+10 45+inf
w
Minimum 45 inf
V6
V1Vw Inf
V1V3V4V2V5Vw 45+inf
Minimum inf
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 second law 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 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 greedy method to obtain a minimum-cost spanning tree builds this tree edge by edge.
The next edge to include is chosen according to some optimization criterion. The simplest
such criterion is to choose an edge that results in a minimum increase in the sum of the
costs of the edges so far included. There are two possible ways to interpret this criterion.
In the first, the set of edges so far selected form a tree. Thus, if A is the set of edges
selected so far, then A forms a tree. The next edge(u,v) to be included in A is a
minimum-cost edge not in A with the property that A U {(u,v)} is also a tree. The
corresponding algorithm is known as prim’s algorithm.
For Prim’s algorithm draw n isolated vertices and label them v1, v2, v3,…vn. Tabulate
the given weights of the edges of g in an n by n table. Set the non existent edges as very
large. Start from vertex v1 and connect it to its nearest neighbor (i.e., to the vertex,
which has the smallest entry in row1 of table) say Vk. Now consider v1 and vk as one
subgraph and connect this subgraph to its closest neighbor. Let this new vertex be vi.
Next regard the tree with v1 vk and vi as one subgraph and continue the process until all
n vertices have been connected by n-1 edges.
Consider the graph shown in fig 7.3. There are 6 vertices and 12 edges. The weights are
tabulated in table given below.
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.
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
V5 to v6 = 9
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
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.
Vertex v belonging to V all vertices u such that there is a path from v to u. This latter
problem can be solved by starting at vertex v and systematically searching the graph G
for vertices that can be reached from v. The 2 search methods for this are :
1) Breadth first search.
2) Depth first search.
In Breadth first search we start at vertex v and mark it as having been reached. The vertex
v at this time is said to be unexplored. A vertex is said to have been explored by an
algorithm when the algorithm has visited all vertices adjacent from it. All unvisited
vertices adjacent from v are visited next. There are new unexplored vertices. Vertex v has
now been explored. The newly visited vertices have not been explored and are put onto
the end of the list of unexplored vertices. The first vertex on this list is the next to be
explored. Exploration continues until no unexplored vertex is left. The list of unexplored
vertices acts as a queue and can be represented using any of the standard queue
representations.
A depth first search of a graph differs from a breadth first search in that the
exploration of a vertex v is suspended as soon as a new vertex is reached. At this time the
exploration of the new vertex u begins. When this new vertex has been explored, the
exploration of u continues. The search terminates when all reached vertices have been
fully explored. This search process is best-described recursively.
Algorithm DFS(v)
{
visited[v]=1
for each vertex w adjacent from v do
{
If (visited[w]=0)then
DFS(w);
}
}
A heap is a complete binary tree with the property that the value at each node is atleast as
large as the value at its children.
The definition of a max heap implies that one of the largest elements is at the root of the
heap. If the elements are distinct then the root contains the largest item. A max heap can
be implemented using an array an[ ].
To insert an element into the heap, one adds it “at the bottom” of the heap and then
compares it with its parent, grandparent, great grandparent and so on, until it is less than
or equal to one of these values. Algorithm insert describes this process in detail.
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 maximum elements
from the max heap a[1..n] can be deleted by deleting the root of the corresponding
Algorithm Adjust(a,I,n)
{
j=2I;
item=a[I];
while (j<=n) do
{
if ((j<=n) and (a[j]< a[j+1])) then
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)
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 sorting
algorithm 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;
}
}
References:
CYCLE
1. Write a program that inputs three numbers and outputs them in ascending order.
2. Write a program to test whether the three numbers represent the sides of a right angle
triangle.
3. Write a program to test whether a given point p(x,y) lies on x-axis or y-axis or in
I/II/III/IV quadrant.
4. Write a program to compute the area of a circle
5. Write a program to compute the circumference of a circle
6. Write a program to find the roots of a quadratic equation.
7. Write a program to list all prime numbers between two limits n1 and n2
8. Write a program to find whether a given number is prime or not.
9. Write programs to implement the sorting techniques.
10. Write programs to implement the searching techniques.
11. Write a program to find the factorial of a number
12. Write a program to exchange the values of two variables with and without using a
temporary variable
13. Write a program to find the number of students who have scored above 60 percent
14. Write a program to find the sum of n numbers
15. Write a program to find the average of n numbers
16. Write a program to find the factorial of a number
17. Write a recursive function to find the factorial of a number.
18. Write a program to implement the binary search
19. Write a program to implement the sequential search
20. Write a program for the method of selection sort
21. Write a program for the method of merge sort
22. Write a recursive and iterative program for reversing a number
23. Write recursive and iterative program to find maximum and minimum in a list of
numbers.
1) Explain the different properties of an algorithm. Bring out the difference between
definiteness and effectiveness of an algorithm.
2) Briefly explain the traveling salesman problem.
3) Explain and illustrate divide and conquer algorithm to search an element.
4) Explain and illustrate divide and conquer algorithm to sort a set of elements.
5) Explain a general algorithm to find the maximum and minimum of n elements in a
list.
6) Obtain an optimal merge pattern for sorted files with lengths (2,3,5,7,9,13) using
greedy method.
7) Explain the principle of greedy method. Find an optimal sequencing of jobs, given
N=7, (p1,…,p7) = (3,5,20,18,1,6,30) (d1,…,d7) = (1,3,4,3,2,1,2).
8) Describe prim’s algorithm to determine a minimum cost spanning tree.
9) Explain recursive and non-recursive algorithms.
10) Write a module, which multiplies two single digit integers using repeated addition
algorithm. Hand simulate the algorithm to compute 52*49.
11) Demonstrate a procedure with an example to create Hash table.
12) Demonstrate the stage by stage implementation of Backtracking method to solve a
4queen problem.
13) Demonstrate the stage by state implementation of Branch and Bound method to
solve 4 queen problem.
14) Discuss Briefly the 8-queen’s problem
2) Illustrate any two sorting techniques and 2 searching techniques. Show all hand
computations step by step clearly. Write down the algorithm with necessary details.
Comment on the performance of the algorithm.