Professional Documents
Culture Documents
A stack is a container of objects that are inserted and removed according to the
last-in first-out (LIFO) principle. In the pushdown stacks only two operations are
allowed:
a) push the item into the stack, and
b) pop the item out of the stack.
By this definition, we can draw a conclusion that every connected and undirected
4. Define Graph.
G = (V,E)
In an undirected graph the pair of vertices representing any edge is
unordered. Thus, the pairs (v1, v2) and (v2, v1) represent the same edge.
In a directed graph each edge is represented by a directed pair (v1, v2). v1 is
the tail and v2 the head of the edge.
Ex:
1 1
1
2 3
2 3
2
4 5 6 7
4
3
5. What is an Algorithm?
3.Definitenes
Each instruction is clear and unambiguous.
4.Finiteness
If. we trace out the instructions of an algorithm, then for all cases, the algorithm
terminates after a finite number of steps.
5. Effectiveness
Every instruction must be very basic so that it can be carried out, in principle, by a person
using only pencil and paper.
6. Write the straightforward procedure to find the max and min in a given set of data.
AlgorithmStraightMaxMin(a,n,max,min)
{
max:=min:=a[l];
for i :=2 to n do
{
if (a[i]>max)thenmax:=a[i];
if (a[i)<min) thenmin :=a[i];
}
}
7. What is meant by Greedy method?
A greedy method is an algorithm that follows the problem solving heuristic of making
the locally optimal choice at each stage with the hope of finding a global optimum.
Graph coloring is nothing but a simple way of labelling graph components such as
vertices, edges, and regions under some constraints. In a graph, no two adjacent vertices,
adjacent edges, or adjacent regions are colored with minimum number of colors. This number is
called the chromatic number and the graph is called a properly colored graph.
A stack is a container of objects that are inserted and removed according to the last-in
first-out (LIFO) principle. In the pushdown stacks only two operations are allowed:
a) push the item into the stack, and
b) pop the item out of the stack.
Associated with the object stack there are several operations that are
necessary:
DELETE (S) / POP( ) which removes the top element of stack S and returns the
new stack;
TOP (S) which returns the top element of stack S;
ISEMTS (S) which returns true if S is empty else false;
These five functions constitute a working definition of a stack. However we
choose to represent a stack, it must be possible to build these operations.
when several stacks and queues co-exist, there was no efficient way to
represent them sequentially. In this we present a good solution to this problem
using linked lists. The following Figure shows a linked stack and a linked
queue. The direction of links for both the stack and queue are such as to facilitate
easy insertion and deletion of nodes.
In the case of figure 1, one can easily add a node at the top or delete one
from the top. In figure 2, one can easily add a node at the rear and both
addition and deletion can be performed at the front, though for a queue we
normally would not wish to add nodes at the front. If we wish to represent n stacks
and m queues simultaneously, then the following set of algorithms and initial
conditions will serve our purpose:
T(i) = Top of ith stack 1<=i<=n
F(i) = Front of ith queue 1<=i<=m
R(i) = Rear of ith queue 1<=i<=m
Initial conditions:
T(i) = 0 1<=i<=n
F(i) = 0 1<=i<=m
Boundary conditions:
T(i) = 0 iff stack i empty
F(i) = 0 iff queue i empty
procedure ADDS(i, Y)
//add element Y onto stack i//
call GETNODE(X)
DATA(X) Y //store data value Y into new node//
LINK(X) T(i) //attach new node to top of ith
stack//
T(i) X //reset stack pointer//
end ADDS
procedure DELETES(i, Y)
if T(i) = 0 then call STACK__EMPTY
X T(i) //set X to top node of stack i//
Y DATA(X) //Y gets new data//
T(i) LINK(X) //remove node from top of stack i//
call RET(X) //return node to storage pool//
end DELETES
procedure ADDQ(i,Y)
//add Y to the ith queue//
call GETNODE(X)
DATA(X) Y: LINK(X) 0
if F(i) = 0 then [F(i) R(i) X] //the queue was
empty//
else [LlNK(R(i)) X;R(i) X] //the queue was
not empty//
end ADDQ
procedure DELETEQ(i, Y)
//delete the first node in the ith queue, set Y to
its DATA field//
if F(i) = 0 then call QUEUE__EMPTY
else [X F(i); F(i) LINK(X)
//set X to front node//
Y DATA(X); call RET(X)] //remove data
and return node//
end DELETEQ
Inorder Traversal: informally this calls for moving down the tree towards the
left until you can go no farther. Then you "visit" the node, move one node to the
right and continue again. If you cannot move to the right, go back one more
node. A precise way of describing this traversal is to write it as a recursive
procedure.
procedure INORDER(T)
//T is a binary tree where each node has three
fields LCHILD,
DATA,RCHILD//
if T 0 then [call INORDER(LCHILD(T))
print(DATA(T))
call(INORDER(RCHILD(T))]
end INORDER
Recursion is an elegant device for describing this traversal. Let us trace how
INORDER works on the tree of figure.
Call of value
INORDER in root Action
MAIN +
1 *
2 /
3 A
4 0 print('A')
4 0 print('/')
3 **
4 B
5 0 print('B')
5 0 print('**')
4 C
5 0 print('C')
5 0 print('*')
2 D
3 0 print('D')
3 0 print('+')
1 E
2 0 print('E')
2 0
procedure PREORDER (T)
//T is a binary tree where each node has three
fields LCHILD,
DATA,RCHILD//
if T 0 then [print (DATA(T))
call PREORDER(LCHILD(T))
call PREORDER(RCHILD(T))]]
end PREORDER
In words we would say "visit a node, traverse left and continue again. When you
cannot continue, move right and begin again or move back until you can move
right and resume.
+* / A ** B C D E
procedure POSTORDER (T)
//T is a binary tree where each node has three
fields LCHILD,
DATA,RCHILD//
if T 0 then [call POSTORDER(LCHILD(T))
call POSTORDER(RCHILD(T))
print (DATA(T))]
end POSTORDER
A pointer to the node which would be printed after P when traversing the
tree in inorder. A null LCHILD link at node P is replaced by a pointer to the node
which immediately precedes node P in inorder. Figure 5.10 shows the binary tree
of figure with its new threads drawn in as dotted lines.
First, we observe that for any node X in a binary tree, if RBIT(X) = 0, then
the inorder successor of X is RCHILD(X) by definition of threads. If RBIT(X) = 1,
then the inorder successor of X is obtained by following a path of left child links
from the right child of X until a node with LBIT = 0 is reached.
procedure INSUC(X)
S RCHILD(X)
if RBIT(X) = 1 then [while LBIT(S) = 1 do
S LCHILD(S)
end]
return (S)
end INSUC
procedure TINORDER (T)
HEAD T
loop
T INSUC(T)
if T = HEAD then return
print(DATA(T))
forever
end TINORDER
13. (a) Write an algorithm for searching an element using Binary search method. Give and
example.
Let ai, 1<i <n, be a list of elements that are sorted in non-decreasing order. Consider the
problem of determining whether a given element x is presenting the list. If x is present,we are to
determine a value j such that aj = x. If x is not in the list, then j is to be set to zero.
Let P = (n,ai,al,.x,) denote an arbitrary instance of this search problem (n is the number of
elements in the list,ai…alis the list of elements, and x is the element searched for).
Divide-and-conquecran be usedto solve this problem.Let Small(P) be true if n = 1.In this
case,S(P)will take the value i if x = ai, otherwise it will take the value 0.Then g(l) = 0(1).If P has
more than one element,it can be divided (or reduced)into a new subproblem as follows. Pick an
index q (in the range [i,l])and compare x with aq. There are three possibilities:
(1) x =aq: In this case the problem P is immediately solved.
(2) x < aq: In this case x has to be searched for only in the sublist ai,,ai+1,…aq-1.
(3) x > aq: In this case the sublist to be searched is aq+1,.,.al. P reduces to (l=q,aq+1,….al,x).
All of the operations such as comparisons between x and a[mid] are well defined. The relational
operators carry out the comparisons among elements of a correctly if these
operators are appropriately defined.
13. (b) Write a procedure to finding the maximum and minimum elements of an array.
Let us consider another simple problem that can be solved by the divide and-conquer
technique.The problem is to find the maximum and minimum items in a set of n elements.The
following Algorithmis a straightforward algorithm to accomplish this.
Algorithm StraightMaxMin(a,n,max,min)
{
max:=min:=a[1];
for i :=2 to n do
{
if (a[i]>max)then max:=a[i];
if (a[i)<min) then min :=a[i];
}
}
Now the best case occurs when the elementsare in increasing order. The number of element
comparisons is n-1.The worst case occurs when the elements are in decreasing order. In this case
the numberof element comparison is 2(n-1).The average number of element comparison is less
than 2(n-1).
MaxMin is a recursive algorithm that finds the maximum and minimum of the set of
elements {a(i),a(i +1),.a.(j.)}. The situation of set sizes one (i = j) and two (i = j-1) are handled
separately. For sets containing more than two elements, the midpoint is determined(just as in
binary search)and two new sub problems are generated. When the maxima and minima of these
sub problems are determined, the two maxima are compared and the two minima are compared
to achieve the solution for the entire set.
14. (a) What is Greedy method? Give general algorithm for it.
The greedy method is perhaps the most straightforward design technique. Any subset that
satisfies those constraints is called a feasible solution. We need to find a feasible solution that
either maximizes or minimizes a given objective function. A feasible solution that does this is
called an optimal solution.
Considering one input at a time.At each stage,a decision is made regarding whether a
particular input is in an optimal solution. This is done by considering the inputs in an order
determined by some selection procedure. If the inclusion of the next input into the partially
constructed optimal solution will result in an infeasible solution, then this input is not added to
the partial solution. Otherwise, it is added. The selection procedure itself is based on some
optimization measure. This measure may be the objective function.
In fact, several different optimization measures may be plausible for a given problem.
Most of these, however, will result in algorithms that generate sub optimal solutions. This
version of the greedy technique is called the subset paradigm.
14. (b) Explain General procedure for Optimal Merge Pattern.
Two sorted files containing n and m records respectively could be merged together to
obtain one sorted file in time 0(n+m). When more than two sorted files are to be merged
together,the merge can be accomplished by repeatedly merging sorted files in pairs.Thus, if files
x1,X2,x3 and x4 are to be merged, we could first merge x1 and x2 to get a file y1. Then we could
merge y1 and x3 to get y2.
Finally, we could merge y2 and x4 to get the desired sorted file. Alternatively, we could
first merge x1 and x2 getting y1, then merge x3 and x4 and get y2, and finally merge y1 and y2 and
get the desired sorted file. Given n sorted files, there are many ways in which to pair wise merge
them into a single sorted file.
Different pairings require differing amounts of computing time. The problem we address
ourselves to now is that of determining an optimal way pairwise merge n sorted files. Since this
problem calls for an ordering among the pairs to be merged,it fits the ordering paradigm.
The merge pattern such as the one just described will be referred to as a two-way merge
pattern. The two-way merge patterns can be represented by binary merge trees. The follwoing
figure shows a binary merge tree representing the optimalmerge pattern obtained for the above
five files. The leaf nodes are drawn as squares and represent the given five files. These nodes are
called external nodes.The remaining nodes are drawn as circles and are called internal nodes.
Each internal node has exactly two children,and it represents the file obtained by merging the
files represented by its two children.The number in each node is the length of the file represented
by that node.
The length of xi is then the total number of record moves for this binary merge tree is
n
∑ diqi
i=1
This sum is called the weighted external path length of the tree.
15. (a) Describe the general method of backtracking.
Backtracking representsone of the most general technique. In many applications of the
backtrack method,the desired solution is expressible as an n-tuple (xi,.,.xn),where the xi are
chosen from some finite set Si. Often the problem to be solved calls for finding one vector that
maximizes a criterion function P(x1,...xn). Sometimes it seeks allvectors that satisfy P.
Suppose mi is the size of set Si.Then there are m = m1m2...mn n-tuples that are possible
candidates for satisfying the function P.The brute force approach would be to form all these n-
tuples evaluate each one with P, and save those which yield the optimum.The backtrack
algorithm has as its virtue the ability to yield the same answer with far fewer than m trials.
Many of the problems we solve using backtracking require that all the solutions satisfy a
complex set of constraints.For any problem these constraints can be divided into two categories:
a) explicit
b) implicit
Definition -1:
Explicit constraints are rules that restrict each xi to take on values only from a given set.
Definition -2:
The implicit constraints are rules that determine which of the tuples in the solution space
of I satisfy the criterion function. Thus implicit constraints describe the way in which the Xi must
relate to each other.
The average of thesefive trialsis 1625. The totalnumberof nodesin the 8-queens state
space tree is
7 j
l +∑[∏i=o(8-i]=69,281
j=0
16. Explain about implementation of Stack and Queue with its operations.
A stack is a data structure used to store a collection of objects. Individual items
can be added and stored in a stack using a push operation. Objects can be retrieved
using a pop operation, which removes an item from the stack.
Implementation of Stack
Stack can be easily implemented using an Array or a Linked List. Arrays are quick, but
are limited in size and Linked List requires overhead to allocate, link, unlink, and deallocate, but
is not limited in size. Here we will implement Stack using array.
Operation :
Associated with the object stack there are several operations that are necessary:
DELETE (S) / POP( ) which removes the top element of stack S and returns the
new stack;
TOP (S) which returns the top element of stack S;
ISEMTS (S) which returns true if S is empty else false;
These five functions constitute a working definition of a stack. However we
choose to represent a stack, it must be possible to build these operations.
structure STACK (item)
declare CREATE ( ) stack
ADD (item, stack) stack
DELETE (stack) stack
TOP (stack) item
ISEMTS (stack) boolean;
for all S stack, i item let
ISEMTS (CREATE) :: = true
ISEMTS (ADD (i,S)) :: = false
DELETE (CREATE) :: = error
DELETE (ADD (i,S)) :: = S
TOP(CREATE) :: = error
TOP(ADD(i,S)) :: = i
end
end STACK
QUEUE:
Queue is an abstract data type or a linear data structure, in which the first
element is inserted from one end called REAR(also called tail), and the deletion of
existing element takes place from the other end called as FRONT(also called head). This
makes queue as FIFO data structure, which means that element inserted first will also be
removed first.
In order to add two polynomials together we examine their terms starting at the nodes pointed to
by A and B. Two pointers p and q are used to move along the terms of A and B. If the exponents
of two terms are equal, then the coefficients are added and a new term created for the result. If
the exponent of the current term in A is less than the exponent of the current term of B, then a
duplicate of the term of B is created and attached to C. The pointer q is advanced to the next
term. Similar action is taken on A if EXP (p) > EXP(q). Figure illustrates this addition process
on the polynomials A and B above.
Each time a new node is generated its COEF and EXP fields are set and it is appended to the end
of the list C. In order to avoid having to search for the last node in C each time a new node is
added, we keep a pointer d which points to the current last node in C. The complete addition
algorithm is specified by the procedure PADD. PADD makes use of a subroutine ATTACH
which creates a new node and appends it to the end of C.
procedure ATTACH(C,E,d)
//create a new term with COEF = C and EXP = E and attach it
to the node pointed at by d//
call GETNODE(I)
EXP(I) E
COEF(I) C
LINK(d) I //attach this node to the end of this list//
d I //move pointer d to the new last node//
end ATTACH
procedure PADD(A,B,C)
p A; q B //p,q pointers to next term of A, B//
call GETNODE(C); d C
while p 0 and q 0 do //while there are more terms in
A and B//
case
: EXP(p) = EXP(q): //equal exponents//
x COEF(p) + COEF(q)
if x 0 then call ATTACH(x, EXP(p),d)
p LINK(p); q LINK(q) //advance to next
terms//
: EXP(p) < EXP(q):
call ATTACH(COEF(q),EXP(q),d)
q LINK(q) //advance to next term//
: else: call ATTACH(COEF(p),EXP(p),d)
p LINK(p) //advance to next term of A//
end
end
while p 0 do //copy remaining terms of A//
call ATTACH(COEF(p),EXP(p),d)
p LINK(p)
end
while q 0 do //copy remaining terms of B//
call ATTACH(COEF(q),EXP(q),d)
q LINK(q)
end
LINK(d) 0; t C; C LINK(C)
call RET(t)
end PADD
In computer science, merge sort or mergesort is a sorting algorithm for rearranging lists
(or any other data structure that can only be accessed sequentially, e.g. file streams) into a
specified order.
It is a particularly good example of the divide and conquer algorithmic paradigm. It is a
comparison sort.
Conceptually, merge sort works as follows:
Divide the unsorted list into two sublists of about half the size
Sort each of the two sublists
Merge the two sorted sublists back into one sorted list.
The strategy:
Merge sort divides the array into two equal halves and sorts the halves separately (using
recursion), then it merges the sorted halves.
The parameters used for merge are: the array name A , and the left, center and right
indexes of the subranges to merge; that is the two sorted sub ranges are A[left]… A
[center+1] ... A[right] (after recursion), and the final sorted array is A[left] ... A[right].
Mergesort sorts the larger amount of data making use of external storage device.
It requires extra memory space.
Recursive mechanism.Pictorially the file can now be viewed as
Where vertical bars indicate the boundaries of subarrays. Elementsa[l] and a[2] are
merged to yield
(285,310| 179| 652,351| 423,861,254, 450,520
At this point the algorithm has returned to the first invocation of MergeSort and is about
to process the second recursive call. Repeated recursive calls are invoked producing the
following sub arrays:
Elements a[6] and a[7] are merged. Then a[8] is merged with a[6:7]:
Next a[9]and a[10] are merged, and then a[Q:8] and a[9:10]:
At this point there are two sorted sub arrays and the final merge produces the fully sorted result