Professional Documents
Culture Documents
BANK
Ans: Algorithm: A step by step process to get the solution for a well‐defined problem.
Properties of an algorithm:
‐ Should be written in simple English
‐ Should be unambiguous, precise and lucid
‐ Should provide the correct solutions
‐ Should have an end point
‐ The output statements should follow inpu t, process instructions
‐ The initial statements should be of input statements
‐ Should have finite number of steps
‐ Every statement should be definitive
Types of algorithms:
‐‐ Simple recursive algorithms. Ex: Searching an element in a list
– Backtracking algorithms Ex: Depth‐first recursive search in a tree
– Divide and conquer algorithms. Ex: Quick sort and merge sort
– Dynamic programming algorithms. Ex: Generation of Fibonacci series
– Greedy algorithms Ex: Counting currency
– Branch and bound algorithms. Ex: Travelling salesman (visiting each city once and
minimize the total distance travelled)
– Brute force algorithms. Ex: Finding the best path for a travelling salesman
– Randomized algorithms. Ex. Using a random number to choose a pivot in quick
sort).
Ques 2:Define in brief an array. What are the types of array operations?
Ans: An array is a set of homogeneous elements. Every element is referred by an index.
Arrays are used for storing the data until the application expires in the main
memory of the computer system. So that, the elements can be accessed at any time. The
operations are:
‐ Adding elements
‐ Sorting elements
‐ Searching elements
‐ Re‐arranging the elements
‐ Performing matrix operations
‐ Pre‐fix and post‐fix operations
Ques 3:Define a linear and nonlinear data structure.
Ans: Linear data structure: A linear data structure traverses the data elements sequentially,
in which only one data element can directly be reached. Ex: Arrays, Linked Lists.
Non‐Linear data structure: Every data item is attached to several other data items in a way
that is specific for reflecting relationships. The data items are not arranged in a sequential
structure. Ex: Trees, Graphs
Ques 5: What is a data structure? What are the types of data structures?
Ans: The scheme of organizing related information is known as ‘data structure’. The types
of data structure are:
Lists: A group of similar items with connectivity to the previous or/and next data
items.
Arrays: A set of homogeneous values
Records: A set of fields, where each field consists of data belongs to one data type.
Trees: A data structure where the data is organized in a hierarchical structure. This
type of data structure follows the sorted order of insertion, deletion and
modification of data items.
Tables: Data is persisted in the form of rows and columns. These are similar to records,
where the result or manipulation of data is reflected for the whole table.
Ques 6: What is an iterative algorithm?
Ans: The process of attempting for solving a problem which finds successive
approximations for solution, starting from an initial guess. The result of repeated
calculations is a sequence of approximate values for the quantities of interest.
Ques 7:What is an recursive algorithm?
Recursive algorithm is a method of simplification that divides the problem into sub‐
problems of the same nature. The result of one recursion is the input for the next recursion.
The repletion is in the self‐similar fashion. The algorithm calls itself with smaller input
values and obtains the results by simply performing the operations on these smaller values.
Generation of factorial, Fibonacci number series are the examples of recursive algorithms.
Ques 8:What is the Huffman algorithm?
Ans:In Huffman Algorithm, a set of nodes assigned with values if fed to the algorithm.
Initially 2 nodes are considered and their sum forms their parent node. When a new
element is considered, it can be added to the tree. Its value and the previously calculated
sum of the tree are used to form the new node which in turn becomes their parent.
Ques 9: List out the areas in which data structures are applied extensively?
Ans: The name of areas are:
· Compiler Design,
· Operating System,
· Database Management System,
· Statistical analysis package,
· Numerical Analysis,
· Graphics,
· Artificial Intelligence,
· Simulation
Ques 10:What are the major data structures used in the following areas : RDBMS,
Network data model & Hierarchical data model.
Ans: The major data structures used are as follows:
· RDBMS ‐ Array (i.e. Array of structures)
· Network data model ‐ Graph
· Hierarchical data model ‐ Trees
12. Ques 11:What is the difference between NULL AND VOID pointer?
Ans: NULL can be value for pointer type variables.
VOID is a type identifier which has not size.
NULL and void are not same. Example: void* ptr = NULL;
Ans: Memory is reserved using data type in the variable declaration. A programming
language implementation has predefined sizes for its data types.
For example, in C# the declaration int i; will reserve 32 bits for variable i.
A pointer declaration reserves memory for the address or the pointer variable, but not
for the data that it will point to. The memory for the data pointed by a pointer has to be
allocated at runtime.
The memory reserved by the compiler for simple variables and for storing pointer
address is allocated on the stack, while the memory allocated for pointer referenced data at
runtime is allocated on the heap.
Ques 13:What are Arrays?
Ans: An array is a series of elements. These elements are of the same type. Each element
can be individually accessed using an index. For e.g an array of integers. Array elements are
stored one after another (contiguous) in the memory. An array can have more than one
dimension. First element in an array starts with 0.
Ans:
#include<stdio.h>
#include<conio.h>
int i,n;
main()
int a[100],pos;
clrscr();
scanf("%d",&n);
for(i=0;i<=n‐1;i++)
scanf("%d",&a[i]);
printf("On which postion element do you want delete\n");
scanf("%d",&pos);
delete(a,pos,n);
getch();
int j,item;
item=a[pos];
for(j=pos;j<=n‐1;j++)
a[j]=a[j+1];
n=n‐1;
for(i=0;i<=n‐1;i++)
printf("%d\n",a[i]);
Ans:
#include<stdio.h>
#include<conio.h>
int i,len,pos,num;
void main()
int a[100];
void insert(int a[], int, int, int);
clrscr();
scanf("%d",&len);
printf("Enter integers");
for(i=0;i<=len;i++)
scanf("%d",&a[i]);
scanf("%d",&num);
scanf("%d",&pos);
‐‐pos;
insert(a,len,pos,num);
void insert (int a[], int len, int pos, int num)
for(i=len;i>=pos;i‐‐)
a[i+1]=a[i];
a[pos]=num;
if(pos>len)
{
printf("insertion outside the array");
len++;
printf("New array");
for(i=0;i<len;i++)
printf("%d\n",a[i]);
getch();
Ques 17: How can we print the address of a particular element in an array?
Ans:
#include<stdio.h>
#include<conio.h>
void main()
clrscr();
i=0;
while(i<=5)
printf("ADDRESS = %u ",num[i]);
getch();
Ques 18: Run Time Memory Allocation is known as ?
Ans: Allocating memory at runtime is called a dynamically allocating memory. In this, you
dynamically allocate memory by using the new operator when declaring the array, for
example : int grades[] = new int[10];
Ques19: What are the types of array operations?
Ans: The following are the operations which can be performed on an array:
Insertion, Deletion, Search, Sorting, Merging, Reversing and Traversal.
Ques 20: How can we print the address of a particular element in a matrix using
pointers?
Ans:
#include<stdio.h>
#include<conio.h>
main()
{100,200},
{300,400},
{500,600}
};
int *ptr1,i,j,n,m;
clrscr();
ptr1=&a[0][0];
n=3;
m=2;
for(i=0;i<=n‐1;i++)
printf("\n");
for(j=0;j<=m‐1;j++)
printf("%d\t",*ptr1);
ptr1++;
}}
getch();
Ques 21: What are the types of matrix operations?
Ans: The following are the types of matrix operations:
Addition, multiplication, transposition, finding determinant of square matrix, subtraction,
checking whether it is singular matrix or not etc.
Ans: An lvalue was defined as an expression to which a value can be assigned. Is an array an
expression to which we can assign a value? The answer to this question is no, because an
array is composed of several separate array elements that cannot be treated as a whole for
assignment purposes.
x = y;
Additionally, you might want to copy the whole array all at once. You can do so using a
library function such as the memcpy() function, which is shown here:
memcpy(x, y, sizeof(y));
It should be noted here that unlike arrays, structures can be treated as lvalues. Thus, you
canassign one structure variable to another structure variable of the same type, such as
this:
char last_name[25];
char first_name[15];
char middle_init[2];
} NAME;
...
your_name = my_name;
(b) O(2^n)
Ans: The quick sort algorithm is of the divide and conquer type. That means it works by
reducing a sorting problem into several easier sorting problems and solving each of them.
A dividing value is chosen from the input data, and the data is partitioned into three sets:
elements that belong before the dividing value, the value itself, and elements that come
after the dividing value. The partitioning is performed by exchanging elements that are in
the first set but belong in the third with elements that are in the third set but belong in the
first Elements that are equal to the dividing element can be put in any of the three sets the
algorithm will still work properly.
Ques 5: The Merge Sort
Ans: The merge sort is a divide and conquer sort as well. It works by considering the data
to be sorted as a sequence of already‐sorted lists (in the worst case, each list is one element
long). Adjacent sorted lists are merged into larger sorted lists until there is a single sorted
list containing all the elements. The merge sort is good at sorting lists and other data
structures that are not in arrays, and it can be used to sort things that don't fit into
memory. It also can be implemented as a stable sort.
Ans:
#include<stdio.h>
#include<conio.h>
int a[max],n,i;
void main()
void input(void);
clrscr();
input();
getch();
void input(void)
scanf("%d",&n);
printf("\n");
for(i=0;i<=n‐1;i++)
scanf("%d",&a[i]);
radix_sort(a,n);
output(a,n);
int bucket[10][5],buck[10],b[10];
int i,j,k,l,num,div,large,passes;
div=1;
num=0;
large=a[0];
for(i=1;i<n;i++)
if(a[i]>large)
large=a[i];
while(large>0)
num++;
large=large/10;
for(passes=0;passes<num;passes++)
for(k=0;k<10;k++)
buck[k]=0;
for(i=0;i<n;i++)
l=(a[i]/div)%10;
bucket[l][buck[l]++]=a[i];
i=0;
for(k=0;k<10;k++)
for(j=0;j<buck[k];j++)
a[i++]=bucket[k][j];
}
div*=10;
Ans:Unfortunately, the only way to search a linked list is with a linear search, because the
only way a linked list's members can be accessed is sequentially. Sometimes it is quicker to
take the data from a linked list and store it in a different data structure so that searches can
be more efficient.
Ans: The heap is where malloc(), calloc(), and realloc() get memory.
Getting memory from the heap is much slower than getting it from the stack. On the other
hand, the heap is much more flexible than the stack. Memory can be allocated at any time
and deallocated in any order. Such memory isn't deallocated automatically; you have to call
free().
Recursive data structures are almost always implemented with memory from the heap.
Strings often come from there too, especially strings that could be very long at runtime. If
you can keep data in a local variable (and allocate it from the stack), your code will run
faster than if you put the data on the heap. Sometimes you can use a better algorithm if you
use the heap faster, or more robust, or more flexible. Its a tradeoff.
If memory is allocated from the heap, its available until the program ends. That's great if
you remember to deallocate it when you're done. If you forget, it's a problem. A memory
leak is some allocated memory that's no longer needed but isn't deallocated. If you have a
memory leak inside a loop, you can use up all the memory on the heap and not be able to
get any more. (When that happens, the allocation functions return a null pointer.) In some
environments, if a program doesn't deallocate everything it allocated, memory stays
unavailable even after the program ends.
Ans:The answer is the standard library function qsort(). It's the easiest sort by far for
several reasons:
It is already written.
It is already debugged.
It has been optimized as much as possible
Void qsort(void *buf, size_t num, size_t size, int (*comp)(const void *ele1, const void
*ele2));
Ques 10:Sort the given values using Quick Sort?
65 70 75 80 85 60 55 50 45
Ans:
Sorting takes place from the pivot value, which is the first value of the given
elements, this is marked bold. The values at the left pointer and right pointer are
indicated using L and R respectively.
65 70L 75 80 85 60 55 50 45R
Since pivot is not yet changed the same process is continued after interchanging the
values at L and R positions
65 45 75L 80 85 60 55 50R 70
65 45 50 80L 85 60 55R 75 70
65 45 50 55 85L 60R 80 75 70
65 45 50 55 60R 85L 80 75 70
When the L and R pointers cross each other the pivot value is interchanged with the value
at right pointer. If the pivot is changed it means that the pivot has occupied its original
position in the sorted order (shown in bold italics) and hence two different arrays are
formed, one from start of the original array to the pivot position‐1 and the other from pivot
position+1 to end.
60L 45 50 55R 65 85L 80 75 70R
The answer depends on what you mean by quickest. For most sorting problems, it just
doesn't matter how quick the sort is because it is done infrequently or other operations
take significantly more time anyway. Even in cases in which sorting speed is of the essence,
there is no one answer. It depends on not only the size and nature of the data, but also the
likely order. No algorithm is best in all cases. There are three sorting methods in this
author's toolbox that are all very fast and that are useful in different situations. Those
methods are quick sort, merge sort, and radix sort.
STACK follows LIFO. Thus the item that is first entered would be the last removed.
In array the items can be entered or removed in any order. Basically each member access is
done using index. No strict order is to be followed here to remove a particular element.
Ques 9: Explain the terms Base case, Recursive case, Binding Time, Run‐Time Stack
and Tail Recursion.
Base case: A case in recursion, in which the answer is known when the termination for a
recursive condition is to unwind back.
Recursive Case: A case which returns to the answer which is closer.
Run‐time Stack: A run time stack used for saving the frame stack of a function when every
recursion or every call occurs.
Tail Recursion: It is a situation where a single recursive call is consisted by a function, and
it is the final statement to be executed. It can be replaced by iteration.
Ans: No. Minimal spanning tree assures that the total weight of the tree is kept at its
minimum. But it doesn't mean that the distance between any two nodes involved in the
minimum‐spanning tree is minimum.
Ques 2: Convert the given graph with weighted edges to minimal spanning tree.
Ans : BFS: This can be throught of as being like Dijkstra's algorithm for shortest paths, but
with every edge having the same length. However it is a lot simpler and doesn't need any
data structures. We just keep a tree (the breadth first search tree), a list of nodes to be
added to the tree, and markings (Boolean variables) on the vertices to tell whether they are
in the tree or list.
Depth first search is another way of traversing graphs, which is closely related to preorder
traversal of a tree. Recall that preorder traversal simply visits each node before its children.
It is most easy to program as a recursive routine:
Ans: The Floyd–Warshall algorithm compares all possible paths through the graph between
each pair of vertices. It is able to do this with only V3 comparisons. This is remarkable
considering that there may be up to V2 edges in the graph, and every combination of edges
is tested. It does so by incrementally improving an estimate on the shortest path between
two vertices, until the estimate is known to be optimal.
There are two candidates for this path: either the true shortest path only uses nodes in the
set {1, ..., k}; or there exists some path that goes from i to k + 1, then from k + 1 to j that is
better. We know that the best path from i to j that only uses nodes 1 through k is defined by
shortestPath(i, j, k), and it is clear that if there were a better path from i to k + 1 to j, then
the length of this path would be the concatenation of the shortest path from i to k + 1 (using
vertices in {1, ..., k} and the shortest path from k + 1 to j (also using vertices in {1, ..., k}).
This formula is the heart of Floyd–Warshall. The algorithm works by first computing
shortestPath(i, j, k) for all (i, j) pairs, then using that to find shortestPath(i, j, 2) for all (i, j)
pairs, etc. This process continues until k = n, and we have found the shortest path for all
(i, j) pairs using any intermediate vertices.
ALGORITHM:
1 /* Assume a function edgeCost(i,j) which returns the cost of the edge from i to j
4 int path[][];
5 /* A 2‐dimensional matrix. At each step in the algorithm, path[i][j] is the shortest path
8 procedure FloydWarshall ()
9 for k := 1 to n
Ans : Dijkstra's algorithm solves the single‐source shortest‐path problem when all edges
have non‐negative weights. It is a greedy algorithm and similar to Prim's algorithm.
Algorithm starts at the source vertex, s, it grows a tree, T, that ultimately spans all vertices
reachable from S. Vertices are added to T in order of distance i.e., first S, then the vertex
closest to S, then the next closest, and so on. Following implementation assumes that graph
G is represented by adjacency lists.
DIJKSTRA (G, w, s)
S ← S È {u}
// Perform relaxation for each vertex v adjacent to u
Relax (u, v, w)
Analysis
Step1. Given initial graph G=(V, E). All nodes nodes have infinite cost except the source
node, s, which has 0 cost.
Step 2. First we choose the node, which is closest to the source node, s. We initialize d[s] to
0. Add it to S. Relax all nodes adjacent to source, s. Update predecessor (see red arrow in
diagram below) for all nodes updated.
Step 3. Choose the closest node, x. Relax all nodes adjacent to node x. Update predecessors
for nodes u, v and y (again notice red arrows in diagram below).
Step 4. Now, node y is the closest node, so add it to S. Relax node v and adjust its
predecessor (red arrows remember!).
Step 5. Now we have node u that is closest. Choose this node and adjust its neighbor node v.
Step 6. Finally, add node v. The predecessor list now defines the shortest path from each
node to the source node, s.
Ques 6: Does dijkstra's algorithm for shortest path provide the optimal solution ?
Ans : Yes,dijkstra's algorithm for shortest path provide the optimal solution.
To find the shortest path between points, the weight or length of a path is calculated as the
sum of the weights of the edges in the path. A path is a shortest path is there is no path
from x to y with lower weight. Dijkstra's algorithm finds the shortest path from x to y in
order of increasing distance from x. That is, it chooses the first minimum edge, stores this
value and adds the next minimum value from the next edge it selects. It starts out at one
vertex and branches out by selecting certain edges that lead to new vertices. It is similar to
the minimum spanning tree algorithm, in that it is "greedy", always choosing the closest
edge in hopes of an optimal solution.
Dijkstra's algorithm selects an arbitrary starting vertex and then branches out from the
tree constructed so far. Each of the nodes it visits could be in the tree, in the fringes or
unseen. The designators:
Ans: Like Kruskal's algorithm, Prim's algorithm is based on a generic MST algorithm. The
main idea of Prim's algorithm is similar to that of Dijkstra's algorithm for finding shortest
path in a given graph. Prim's algorithm has the property that the edges in the set A always
form a single tree. We begin with some vertex v in a given graph G =(V, E), defining the
initial set of vertices A. Then, in each iteration, we choose a minimum‐weight edge (u, v),
connecting a vertex v in the set A to the vertex u outside of set A. Then vertex u is brought
in to A. This process is repeated until a spanning tree is formed. Like Kruskal's algorithm,
here too, the important fact about MSTs is we always choose the smallest‐weight edge
joining a vertex inside set A to the one outside the set A. The implication of this fact is that
it adds only edges that are safe for A; therefore when the algorithm terminates, the edges in
set A form a MST.
Algorithm
MST_PRIM (G, w, v)
1. Q ← V[G]
2. for each u in Q do
3. key [u] ← ∞
4. key [r] ← 0
5. π[r] ← NIl
6. while queue is not empty do
7. u ← EXTRACT_MIN (Q)
8. for each v in Adj[u] do
9. if v is in Q and w(u, v) < key [v]
10. then π[v] ← w(u, v)
11. key [v] ← w(u, v)
Analysis
The performance of Prim's algorithm depends of how we choose to implement the priority
queue Q.
Definitions Sparse graphs are those for which |E| is much less than |V|2 i.e., |E| << |V|2 we
preferred the adjacency‐list representation of the graph in this case. On the other hand,
dense graphs are those for which |E| is graphs are those for which |E| is close to |V|2. In this
case, we like to represent graph with adjacency‐matrix representation.
Trees
Ques 1: What is a B tree?
Ans A B‐tree of order m (the maximum number of children for each node) is a tree
which satisfies the following properties :
Ans:
A binary tree is a tree structure, in which each node has only two child nodes. The first
node is known as root node. The parent has two nodes namely left child and right child.
Uses of binary tree:
‐ To create sorting routine.
‐ Persisting data items for the purpose of fast lookup later.
‐ For inserting a new item faster
Ans:
struct BINARY_S_TREE
BINARY_S_TREE *left;
int info;
BINARY_S_TREE *right;
};
BINARY_S_TREE *root;
BINARY_S_TREE *loc;
loc=root_loc;
if(loc!=NULL)
cout<<loc‐>info<<"‐>";
RECURSION_preorder(loc‐>left);
RECURSION_preorder(loc‐>right);
Ans:
struct BINARY_S_TREE
BINARY_S_TREE *left;
int info;
BINARY_S_TREE *right;
};
BINARY_S_TREE *root;
BINARY_S_TREE *FRESH;
if(data==loc‐>info)
cout<<"DUPLICATE VALUE\n";
return;
else if(data<loc‐>info)
if(loc‐>left != NULL)
create(loc‐>left,data);
else
cout<<"INSERTING TO LEFT\n";
FRESH=new BINARY_S_TREE;
FRESH‐>info=data;
FRESH‐>left=FRESH‐>right=NULL;
loc‐>left=FRESH;
else
{
if(loc‐>right != NULL)
create(loc‐>right,data);
else
cout<<"INSERTING TO RIGHT\n";
FRESH=new BINARY_S_TREE;
FRESH‐>info=data;
FRESH‐>left=FRESH‐>right=NULL;
loc‐>right=FRESH;
}}
Ans:
else
5. return