You are on page 1of 36

1. Define Stack and Queue and also write its basic operations.

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.

A queue is a container of objects (a linear collection) that are inserted and


removed according to the first-in first-out (FIFO) principle. In the queue only two
operations are allowed enqueue and dequeue.
a) Enqueue means to insert an item into the back of the queue,
b) dequeue means removing the front item.

2. What is meant by Linked Queue?


The queue which is implemented using linked list can work for unlimited number of
values. That means, queue using linked list can work for variable size of data (No need to fix
the size at beginning of the implementation). The Queue implemented using linked list can
organize as many data values as we want.
In linked list implementation of a queue, the last inserted node is always pointed by 'rear'
and the first node is always pointed by 'front'.
3. Define : Spanning Tree
A spanning tree is a subset of Graph G, which has all the vertices covered with minimum
possible number of edges. Hence, a spanning tree does not have cycles and it cannot be
disconnected.

By this definition, we can draw a conclusion that every connected and undirected

Graph G has at least one spanning tree.

4. Define Graph.

A graph, G, consists of two sets V and E. V is a finite non-empty set of


vertices. E is a set of pairs of vertices, these pairs are called edges. V(G) and E(G)
will represent the sets of vertices and edges of graph G.

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?

An algorithm is a finite set of instructions that, if followed, accomplishes a particular


task. In addition, all algorithms must satisfy the following criteria:
1.Input.
Zero or more quantities are externally supplied.
2. Output.
At least one quantity is produced.

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.

8. Define : Knapsack Problem.


Knapsack problem is defined as “It is a greedy method in which knapsack is nothing but
a bag which consists of n objects each objects an associated with weight and profit”.
9. Define the term : Backtracking.
Backtracking can be defined as a general algorithmic technique that considers searching
every possible combination in order to solve an optimization problem.

10. What is Graph Coloring?

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.

11.(a) Explain about operations on Stack.

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:

 CREATE (S) which creates S as an empty stack;


 ADD (i,S) / PUSH ( ) which inserts the element i onto the stack S and returns the
new stack;

 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.

11. (b) Explain the structure of linked stacks and queues.

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 i­th 
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

12. (a) Explain Binary Tree traversal with example.


When traversing a binary tree we want to treat each node and its subtrees in the same
fashion. If we let L, D, R stand for moving left, printing the data, and moving right when at a
node then there are six possible combinations of traversal: LDR, LRD, DLR, DRL, RDL, and
RLD.
If we adopt the convention that we traverse left before right then only three traversals
remain: LDR, LRD and DLR. To these we assign the names inorder, postorder and preorder
because there is a natural correspondence between these traversals and producing the infix,
postfix and prefix forms of an expression. Consider the binary tree of figure. This tree contains
an arithmetic expression with binary operators: add(+), multiply(*), divide(/), exponentiation(**)
and variables A, B, C, D, and E.

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

The elements get printed in the order


A/B ** C * D + E

which is the infix form of the expression.

A second form of traversal is preorder:

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

which we recognize as the prefix form of the expression.

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

The output produced by POSTORDER is


A B C ** / D * E +
which is the postfix form of our expression.

12. (b) Explain briefly about threaded binary trees.

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.

If we traverse T in inorder the nodes will be visited in the order H D I B E A F C


G. For example node E has a predecessor thread which points to B and a successor
thread which points to A.

In the memory representation we must be able to distinguish between threads and


normal pointers. This is done by adding two extra one bit fields LBIT and RBIT.
LBIT(P) =1 if LCHILD(P) is a normal pointer
LBIT(P) = 0 if LCHILD(P) is a thread
RBIT(P) = 1 if RCHILD(P) is a normal pointer
RBIT(P) = 0 if RCHILD(P) is a thread

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.

Algorithm Recursive binary search


AlgorithmBinSrch(a, i,l,x)
{
if (l=i) then
{
if (x = a[i]) then return i;
else return 0;
}
else
{// ReduceP into a smallersubproblem.
mid:=[(i+l)/2];
if (x = a[mid]) then return mid;
else if (x <a[mid]) then
return BinSrch(a,i, mid-1,x);
elsereturnBinSrch(a,mid+1,l,x);
}
}

Algorithm Iterativebinary search


AlgorithmBinSearch(a,n,x)
{
low :=1;high :=n;
while (low<=high) do
{
mid:= [(low+high)/2];
if (x <a[mid])then high :=mid-1;
else if (x >a[mid])then low :=mid+ 1;
else return mid;
} return0;
}

Ex : Select the 14 entries

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.

Algorithm MaxMin(i, j,max, min)


{
if (i = j) then max:=min:=a[i];
else if (i = j - 1) then
{
if (a[i]<a[j])then
{
max :=a[j];min :=a[i]
}
else
{
max:=a[i]; min:=a[j];
}
}
else
{
mid:=[(i+j)/2;
MaxMin(i,mid,max,min);
MaxMin(mid+1,j,max1,min1);
if (max<max1) then max:=max1;
if (min >min1)then min:=min1;
}
}

The procedureis initially invokedby the statement


MaxMin(l,n,x,y)
Supposewe simulateMaxMin on the following nineelements:
a: [1] [2] [3] [4] [5] [6] [7] [8] [9]
22 13 -5 -8 15 60 17 31 47

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.

15. (b) Explain the 8-Queens problem.

A classic combinatorial problem is to place eight queens on an 8 x 8 chessboard so that


no two "attack", that is, so that no two of them are on the same row, column, or diagonal. Let us
number the rows and columns of the chessboard 1 through 8.The queens can also be numbered 1
through 8.Since each queen must be on a different row, we can without loss of generality assume
queen i is to be placed on row i. All solutions to the 8-queens problem can therefore be
represented as 8-tuples(x1,..,.x8),where Xi is the columnon which queen i is placed. The explicit
constraints using this formulation are Si = {1,2,3,4,5,6,7, 8}, 1< i < 8.Therefore the solution space
consists of 88 8-tuples.
At this point we might wonder how effective function N-Queens is over the brute force
approach. For an 8 x8 chessboard there are ( ) possible ways to place 8 pieces,or approximately
4.4 billion 8-tuples to examine.However,by allowing only placements of queens on distinct rows
and columns,we require the examinationof at most 8!,or only 40,320 8-tuples.

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.

Basic features of Stack

A. Stack is an ordered list of similar data type.


B. Stack is a LIFO structure. (Last in First out).
C. push() function is used to insert new elements into the Stack and pop() is used to
delete an element from the stack. Both insertion and deletion are allowed at only
one end of Stack called Top.
D. Stack is said to be in Overflow state when it is completely full and is said
to be in Underflow state if it is completely empty.

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:

 CREATE (S) which creates S as an empty stack;


 ADD (i,S) / PUSH ( ) which inserts the element i onto the stack S and returns the
new stack;

 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

procedure ADD (item, STACK, n, top)


//insert item into the STACK of maximum size n; top is the number
of elements curently in STACK//
if top n then call STACK_FULL
top top + 1
STACK (top) item
end ADD

procedure DELETE (item, STACK, top)


//removes the top element of STACK and stores it in item
unless STACK is empty//
if top 0 then call STACK_EMPTY
item STACK (top)
top top - 1
end DELETE

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.

 Queue can be implemented using an Array, Stack or Linked List.


 The easiest way of implementing a queue is by using an Array.
 Initially the head(FRONT) and the tail(REAR) of the queue points at the first index of the
array (starting the index of array from 0).
 As we add elements to the queue, the tail keeps on moving ahead, always pointing to the
position where the next element will be inserted, while the head remains at the first index.
 When we remove element from Queue, we can follow two possible approaches.
 In first approach, we remove the element at head position, and then one by one move all
the other elements on position forward. In second approach we remove the element from
head position and then move head to the next position.
 In first approach there is an overhead of shifting the elements one position forward every
time we remove the first element.
 In second approach , there is no such overhead, but whenever we move head one position
ahead, after removal of first element, the size on Queue is reduced by one space each
time.
Types of Operation in queue:
 Queue() creates a new queue that is empty. It needs no parameters and returns an empty
queue.
 Enqueue(item) adds a new item to the rear of the queue. It needs the item and returns
nothing.
 Dequeue() removes the front item from the queue. It needs no parameters and returns the
item. The queue is modified.
 IsEmpty() tests to see whether the queue is empty. It needs no parameters and returns a
boolean value.
 Size() returns the number of items in the queue. It needs no parameters and returns an
integer.
A complete specification of this data structure is

structure QUEUE (item)


declare CREATEQ( ) queue
ADDQ(item,queue) queue
DELETEQ(queue) queue
FRONT(queue) item
ISEMTQ(queue) boolean;
for all Q queue, i item let
ISEMTQ(CREATEQ) :: = true
ISEMTQ(ADDQ(i,Q)) :: = false
DELETEQ(CREATEQ) :: = error
DELETEQ(ADDQ(i,Q)):: =
if ISEMTQ(Q) then CREATEQ
else ADDQ(i,DELETEQ(Q))
FRONT(CREATEQ) :: = error
FRONT(ADDQ(i,Q)) :: =
if ISEMTQ(Q) then i else FRONT(Q)
end
end QUEUE

Q(1) (2) (3) (4) (5) (6) (7) ... Remarks


front rear
0 0 queue empty Initial
0 1 Jl Job 1 joinsQ
0 2 J1 J2 Job 2 joinsQ
0 3 J1 J2 J3 Job 3 joinsQ
1 3 J2 J3 Job 1leaves Q
1 4 J2 J3 J4 Job 4 joinsQ
2 4 J3 J4 Job 2leaves Q

The following algorithms for ADDQ and DELETEQ result:


procedure ADDQ(item, Q, n, rear)
//insert item into the queue represented in Q(l:n)//
if rear = n then call QUEUE_FULL
rear rear + 1
Q(rear) item
end ADDQ
procedure DELETEQ(item, Q, front, rear)
//delete an element from a queue//
if front = rear then call QUEUE_EMPTY
front front + 1
item Q(front)
end DELETEQ
17. How can you represent the polynomial as an ordered list? Also describe the
procedure to find the addition of two polynomials.This problem, the manipulation of
symbolic polynomials, has become a classical example of the use of list processing.
A(x) = amxem + ... + a1xe1
_____________________
| | | |
|COEF | EXP | LINK |
|______|______|_______|

For instance, the polynomial A= 3x14 + 2x8 + 1 would be stored as

while B = 8x14 - 3x10 + 10x6 would look like

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

18. Explain Mergesort Algorithm with example.

 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].

ANALYSIS OF MERGE SORT

WORST CASE ANALYSIS O(N LOG N)


BEST CASE ANALYSIS O(N LOG N)

AVERAGE CASE ANALYSIS O(N LOG N)

Limitations of Merge Sort:

 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

(310| 285| 179| 652,351| 423,861,254, 450,520)

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

Then a[3] is merged with a[l:2] and

(179,285,310| 652,351| 423,861,254, 450,520)

is produced.Next,elements a[4] and a[5] are merged:

(179,285,310| 351,652| 423,861,254, 450,520)


and then a[l:3] and a[4 :5]:

(179,285,310,351,652| 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:

(179,285,310,351,652| 423 | 861| 254 | 450,520)

Elements a[6] and a[7] are merged. Then a[8] is merged with a[6:7]:

(179,285,310,351,652| 254, 423,861| 450,520)

Next a[9]and a[10] are merged, and then a[Q:8] and a[9:10]:

(179,285,310,351,652| 254, 423,450,520,861)

At this point there are two sorted sub arrays and the final merge produces the fully sorted result

(179, 254, 285,310, 351,423, 450,520, 652,861)

19. Describe about Job Sequencing with Deadlines with examples.


We are given a set of n jobs. Associated with job i is an integer deadline d i >0 and a profit
pi >0. For any job i the profit pi is earned iff the job is completed by its deadline. To complete a
job, one has to process the job on a machine for one unit of time. Only one machine is available
for processing jobs.
A feasible solution for this problem is a subset J of jobs such that each job in this subset
can be completed by its deadline. The value of a feasible solution J is the sum of the profits of
the jobs in J, or ∑i€Jpi. An optimal solution is a feasible solution with maximum value. Here
again, since the problem involves the identification of a subset, it fits the subset paradigm.

20. State and explain sum of subsets problem.

You might also like