0% found this document useful (0 votes)
43 views18 pages

BS351 - 1 Data Structure Notes For qp24

Cs notes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views18 pages

BS351 - 1 Data Structure Notes For qp24

Cs notes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Q1) what is Data structure? Give Examples.

Data Structure is a particular way of storing, processing and organizing data in the memory of the
computer so that these data can easily be retrieved and efficiently used in the future as per the
requirement.
Some examples of Data Structures are Arrays, Linked Lists, Stack, Queue, Trees, etc. Data Structures
are widely used in almost every aspect of Computer Science, i.e., Compiler Design, Operating
Systems, Graphics, Artificial Intelligence, and many more.

Q 2) write about analysis of algorithm.


Analysis of algorithms is required to compare and choose the best algorithm for implementation.
Analysis involves measuring the performance of algorithm. Performance can be measured in terms of
the following parameters.
 Time complexity of programmer
 Time complexity of algorithm
 Space complexity of algorithm
Q 3) Applications of stacks.

A stack is a linear data structure in which the insertion of a new element and removal of an existing
element takes place at the same end represented as the top of the stack.
Applications of Stacks:
 Function calls
 Reverse a data
 Recursion
 Expression evaluation
 Syntax parsing
 Memory management
Q 4) Recurrence in data structure
A recurrence is a well-defined mathematical function, where the function being defined is applied
within its own definition.
The problems that can be described using recurrence are easily expressed as recursive functions in
programming. Recursion is useful in situations where one or more smaller version of the same
problem can solve that problem itself.
Example are Fibonacci series, factorial..etc
Q 5) Circular Queue.
A Circular Queue is an extended version of a normal queue where the last element of the queue is
connected to the first element of the queue forming a circle.
n a normal Queue, we can insert elements until queue becomes full. But once queue becomes full, we
can not insert the next element even if there is a space in front of queue.
Operations on Circular Queue:
 Front
 Rear
 Enqueuer()
 dequeuer()

Q 6) linked stack
Linked stack can be defined as stack implementation using linked list. To overcome the limitation of
fixed size allocation, when implementing stacks using arrays , single linked list are used .
Each element in the stack will be represented as a node of the list. Addition and deleteion of the node
will be done only at end.
The first node is considered to be at the top of the stack and pointed by the pointer-top. The second
node is connected through the address field of the first node. The last node is the bottom of the stack
and its link field is set to NULL.

Q 7) ADT for binary tree.


A binary tree
 Is either an empty tree or
 Contains of a node,called root and 2-children, left and right , each of which itself is a binary
tree.
ADT for binary tree:-
ADT btree
1. Declare create() btree
2. Makebtree(btree, element, btree)btree.
3. isEmpty(btree)boolean
4. leftchild(btree)btree
5. rightchild(btree)btree
6. data(btree)element
7. for all l, r € btree, e€ element, Let
8. isEmpty(create)=true
9. isEmpty(makebtree(l,e,r))=false
10. leftchild(create())=error
11. rightchild(create())=error
12. leftchild(makebtree(l,e,r))=l
13. rightchild(makebtree(l.e.r))=r
14. data(makebtree(l,e,r))=e;
15. end
16. end
Q 8)short notes on linear search

A linear search is the simplest and sequential search approach in data structure used to search for an
element in a data set. It examines each element by traversing the list until it finds a match, starting at
the beginning of the data set, until the end. The search is finished and terminated once the target
element is located.
The steps used in the implementation of Linear Search are listed as follows -

 First, we have to traverse the array elements using a for loop.


 In each iteration of for loop, compare the search element with the current array element, and -
 If the element matches, then return the index of the corresponding array element.
 If the element does not match, then move to the next element.
 If there is no match or the search element is not present in the given array, return -1.

Q 9) symbol table
A symbol table is a data structure used by a language translator such as a compiler or interpreter,
where each identifier, symbol, constant, procedure and function in a program's source code is
associated with information relating to its declaration or appearance in the source.
A symbol table is a set of pairs ( name, value), where the value represents the collection of attributes
associated with the name.
The operations performed on symbol tables are :
 Inserting the <key, information> pairs into the collection.
 Removing the <key, informations> pairs by specifying the key
 Searching for a particular key
 Retrieving the information associated with a key

Q 10) Depth first search


It is a graph traversal technique, in which we keep searching deeper wherever possible starting with
currently visited vertex in the graph.
All vertices are visited by processing a vertex and its descendants before processing its adjacent
vertices. This procedure can be written either recursively or non-recursively
Because of the recursive nature, stack data structure can be used to implement the DFS algorithm

Q 11) hash table overflow.


Hash table overflow will occur when a new identifier is mapped or hashed into a full bucket. When
bucket size is one, a Collison and an overflow will occur simultaneously. Therefore, any hashing
program must have some method for dealing with records that can’t fit into their home addresses.
Methods used to handle overflow of records are-Open addressing and chaining

Q 12) Applications of Heap


Heap is a complete binary tree data structure that satisfies the heap property: for every node, the value
of its children is greater than or equal to its own value.
Heaps are commonly used in the following operations:
 Selection problem
 Scheduling and priority Queue
 Sorting

PART-B( 4 X 12= 48 Marks)

Q 13-a) Types of data structures with suitable examples.


Various types of data structures are as follows:

1) Primitive and non-primitive: Primitive data structures define a set of primitive element that don’t
involve any other elements as its sub parts( for example- data structures defined for integers and
characters. ) these are generally primary or built-in data types in programming language.
Non primitive data structures will define a set of derived elements such as arrays, class. That is they
can store that data of many data types. Examples of non-primitive data structure are Array, Linked list,
stack.
2) Linear and non- linear: A linear data structure is a structure in which the elements are stored
sequentially, and the elements are connected to the previous and the next element. As the elements are
stored sequentially, so they can be traversed or accessed. Examples are-are Array, Queue, Stack,
Linked List.
A non-linear data structure is also another type of data structure in which the data elements are not
arranged in a contiguous manner. They are used to represent the data in hierarchical or network
relationship among the elements.. In the case of linear data structure, element is connected to two
elements (previous and the next element), whereas, in the non-linear data structure, an element can be
connected to more than two elements. Trees and Graphs are the types of non-linear data structure.
3) static and dynamic: Static data structures have a fixed size and are allocated in memory during
compile-time, while dynamic data structures can grow and shrink in size during runtime.an Array is
example of static and linked list can be considered as dynamic data structure.
4) persistent and Ephemeral : a data structure that supports operations on the most recent version as
well as the previous version is termed as persistent data structure.
An Ephemeral data structure supports operations on the most recent version of the data only.

5) sequential access and direct access: if any element in the data structure can be accessed without
accessing its previous element, its called as direct access. Array is an example of direct access.
If any data structure allows accessing of one element after accessing its previous element, known as
sequential access. Linked list is an example.

Q 13-b) write a program to evaluate an expression by using stack data structure.

#include<iostream>
#include<cmath>
#include<stack>
using namespace std;
float scanNum(char ch)
{ int value;
value = ch;
return float(value-'0'); //return float from character
}
int isOperator(char ch) {
if(ch == '+'|| ch == '-'|| ch == '*'|| ch == '/' || ch ==
'^') return 1; //character is an operator
return -1; //not an operator
}
int isOperand(char ch)
{ if(ch >= '0' && ch <=
'9')
return 1; //character is an operand
return -1; //not an operand
}
float operation(int a, int b, char op) {
//Perform operation
if(op == '+')
return b+a;
else if(op == '-')
return b-a;
else if(op ==
'*')
return b*a;
else if(op == '/')
return b/a;
else if(op ==
'^')
return pow(b,a); //find b^a
else
return INT_MIN; //return negative infinity
}
float postfixEval(string postfix)
{ int a, b;
stack<float> stk;
string::iterator it;
for(it=postfix.begin(); it!=postfix.end(); it++) {
//read elements and perform postfix evaluation
if(isOperator(*it) != -1) {

a = stk.top();
stk.pop();
b = stk.top();
stk.pop();
stk.push(operation(a, b, *it));
}else if(isOperand(*it) > 0) {
stk.push(scanNum(*it));
}
}
return stk.top();
}
main() {
string post = "53+62/*35*+";
cout << "The result is: "<<postfixEval(post);
}

Q 14 –a) compare iteration and recursion. Explain use of stack in recurrence with implementation.

The following table highlights all the important differences between recursion and
iteration −

Recursion Iteration

 Recursion uses the selection structure.  Iteration uses the repetition structure.

 Infinite recursion occurs if the step in


recursion doesn't reduce the problem to a
 An infinite loop occurs when the
smaller problem. It also becomes infinite
condition in the loop doesn't become
recursion if it doesn't convert on a specific
False ever.
condition. This specific condition is
known as the base case.

 The system crashes when infinite  Iteration uses the CPU cycles again
recursion is encountered. and again when an infinite loop occurs.
 Recursion terminates when the base case  Iteration terminates when the
is met. condition in the loop fails.

 Recursion is slower than iteration since


 Iteration is quick in comparison to
it has the overhead of maintaining and
recursion. It doesn't utilize the
updating the stack.
stack.

 Recursion uses more memory in  Iteration uses less memory


comparison to iteration. in comparison to recursion.

 Recursion reduces the size of the code.  Iteration increases the size of the code.

Use of stack in recursion:


A stack is used in recursion to manage the intermediate results of function calls and to store the return
address. A stack is a data structure that uses a Last In First Out (LIFO) method, meaning that the most
recently added item is the first to be removed.
Here's how a stack is used in recursion:
 Function calls: When a function is called, it is placed on top of the stack.
 Intermediate results: Each function call in a recursive calculation leaves its result on the stack.
 Base case: When the base case is reached, the partial results are removed from the stack and
combined to get the final result.
 Return address: The return address is stored on the stack to tell the computer where to return to
after the function finishes executing.
 Recursion depth: The recursion depth is the maximum number of contexts in the stack.
It is important to note that stack overflow can occur due to limited space available for stack-based
memory. One of the most common causes of stack overflow is infinite recursion,
Q 14-b) linked list variants with examples.
A linked list is a linear data structure, in which the elements are not stored at contiguous memory
locations. The elements in a linked list are linked using pointers. In simple words, a linked list consists
of nodes where each node contains a data field and a reference(link) to the next node in the list.
The following are the types of linked list:
 Singly Linked list
 Doubly Linked list
 Circular Linked list

Singly Linked list


It is the commonly used linked list in programs. The singly linked list is a data structure that contains
two parts, i.e., one is the data part, and the other one is the address part, which contains the address
of the next or the successor node. The address part in a node is also known as a pointer.
Suppose we have three nodes, and the addresses of these three nodes are 100, 200 and 300
respectively. The representation of three nodes as a linked list is shown in the below figure:
in the above figure that there are three different nodes having address 100, 200 and 300 respectively.
The first node contains the address of the next node, i.e., 200, the second node contains the address of
the last node, i.e., 300, and the third node contains the NULL value in its address part as it does not
point to any node. The pointer that holds the address of the initial node is known as a head pointer.

// Definition of a Node in a singly linked list


struct Node {

// Data part of the node


int data;

// Pointer to the next node in the list


Node* next;

// Constructor to initialize the node with data


Node(int data) {
this->data = data;
this->next = nullptr;
}
};

Doubly linked list


As the name suggests, the doubly linked list contains two pointers. We can define the doubly linked
list as a linear data structure with three parts: the data part and the other two address part. In other
words, a doubly linked list is a list that has three parts in a single node, includes one data part, a
pointer to its previous node, and a pointer to the next node.
Suppose we have three nodes, and the address of these nodes are 100, 200 and 300, respectively. The
representation of these nodes in a doubly-linked list is shown below:
in the above figure, the node in a doubly-linked list has two address parts; one part stores the address
of the next while the other part of the node stores the previous node's address. The initial node in the
doubly linked list has the NULL value in the address part, which provides the address of the previous
node.

struct Node
{ int data;
Node* next;
Node* prev;

Node(int x)
{ data = x;
next = nullptr;
prev = nullptr;
}
};

Circular linked list


A circular linked list is a variation of a singly linked list. The only difference between the singly linked
list and a circular linked list is that the last node does not point to any node in a singly linked list, so its
link part contains a NULL value.
On the other hand, the circular linked list is a list in which the last node connects to the first node, so
the link part of the last node holds the first node's address. The circular linked list has no starting and
ending node. We can traverse in any direction, i.e., either backward or forward.
// Define the Node structure
struct Node {
int data;
Node* next;

Node(int value)
{ data = value;
next = nullptr;
}
}

Q 15-a) Different types of trees and applications of binary trees.


Tree data structure is a hierarchical structure that is used to represent and organize data in a way that
is easy to navigate and search. It is a collection of nodes that are connected by edges and has a
hierarchical relationship between the nodes.
The topmost node of the tree is called the root, and the nodes below it are called the child nodes. Each
node can have multiple child nodes, and these child nodes can also have their own child nodes,
forming a recursive structure.
The following are the types of a tree data structure:
General tree: The general tree is one of the types of tree data structure. In the general tree, a node can
have either 0 or maximum n number of nodes. There is no restriction imposed on the degree of the
node (the number of nodes that a node can contain). The topmost node in a general tree is known as a
root node. The children of the parent node are known as subtrees.
Binary tree: Here, binary name itself suggests two numbers, i.e., 0 and 1. In a binary tree, each node in
a tree can have utmost two child nodes. Here, utmost means whether the node has 0 nodes, 1 node or 2
nodes.
Binary Search tree: Binary search tree is a non-linear data structure in which one node is connected to
n number of nodes. It is a node-based data structure. A node can be represented in a binary search tree
with three fields, i.e., data part, left-child, and right-child. A node can be connected to the utmost two
child nodes in a binary search tree, so the node contains two pointers (left child and right child
pointer).
Every node in the left subtree must contain a value less than the value of the root node, and the value
of each node in the right subtree must be bigger than the value of the root node.
AVL tree
It is one of the types of the binary tree, or we can say that it is a variant of the binary search tree. AVL
tree satisfies the property of the binary tree as well as of the binary search tree. It is a self-balancing
binary search tree that obeys the binary search tree as well as a balancing factor.
The balancing factor can be defined as the difference between the height of the left subtree and the
height of the right subtree. The balancing factor's value must be either 0, -1, or 1; therefore, each node
in the AVL tree should have the value of the balancing factor either as 0, -1, or 1.
Applications of Binary Heap Tree
 Expression Trees
Representing arithmetic expressions where internal nodes are operators and leaf nodes are
operands.
Used in compilers and calculators.
 Huffman Coding Tree
Used in data compression algorithms (e.g., Huffman coding for lossless compression).
 Decision Trees
Machine learning algorithms for classification and regression problems.
Representing conditional decision processes.
 Traversal-Based Operations
Preorder, inorder, and postorder traversals for various computations like expression evaluation
or tree reconstruction.
Q 15-b) comparison of various sorting algorithms
Q 16-a) spanning tree using prim’s algorithm

Prim's Algorithm is a greedy algorithm that is used to find the minimum spanning tree from weighted
undirected graph. Prim's algorithm finds the subset of edges that includes every vertex of the graph
such that the sum of the weights of the edges can be minimized.
Prim's algorithm starts with the single node and explores all the adjacent nodes with all the connecting
edges at every step. The edges with the minimal weights causing no cycles in the graph got selected.

The algorithm may informally be described as performing the following steps:

1. Initialize a tree with a single vertex, chosen arbitrarily from the graph.
2. Grow the tree by one edge: Of the edges that connect the tree to vertices not yet in the tree,
find the minimum-weight edge, and transfer it to the tree.
3. Repeat step 2 (until all vertices are in the tree).

Example of prim's algorithm

Suppose, a weighted graph is -

Step 1 - First, we have to choose a vertex from the above graph. Let's choose B.
Step 2 - Now, we have to choose and add the shortest edge from vertex B. There are two edges from
vertex B that are B to C with weight 10 and edge B to D with weight 4. Among the edges, the edge
BD has the minimum weight. So, add it to the MST.

Step 3 - Now, again, choose the edge with the minimum weight among all the other edges. In this
case, the edges DE and CD are such edges. Add them to MST and explore the adjacent of C, i.e., E
and A. So, select the edge DE and add it to the MST.

Step 4 - Now, select the edge CD, and add it to the MST.
Step 5 - Now, choose the edge CA. Here, we cannot select the edge CE as it would create a cycle to the
graph. So, choose the edge CA and add it to the MST.

So, the graph produced in step 5 is the minimum spanning tree of the given graph. The cost of the MST
is given below -

Cost of MST = 4 + 2 + 1 + 3 = 10 units.

Algorithm
1. Step 1: Select a starting vertex
2. Step 2: Repeat Steps 3 and 4 until there are fringe vertices
3. Step 3: Select an edge 'e' connecting the tree vertex and fringe vertex that has minimum weight
4. Step 4: Add the selected edge and the vertex to the minimum spanning tree T
5. [END OF LOOP]
6. Step 5: EXIT
Q 16-b) implementation of heap with an example. Applications of heaps.
A heap is a tree where each parent node is greater than or equal to its child nodes in a max-heap or less
than or equal to its child nodes in a min-heap. This means the largest or smallest value is always at the
top (root) of the tree
Applications of Heaps:

You might also like