0% found this document useful (0 votes)
3 views25 pages

Dsa Lab Manual

The document outlines a series of practical exercises for a Data Structures and Algorithms laboratory course, including implementations of various data structures such as stacks, queues, binary search trees, AVL trees, and algorithms like Dijkstra's and Prim's. Each exercise includes an aim, algorithm, program code in Python, and results confirming successful implementation. The document emphasizes the educational mapping of these exercises to specific program outcomes.
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)
3 views25 pages

Dsa Lab Manual

The document outlines a series of practical exercises for a Data Structures and Algorithms laboratory course, including implementations of various data structures such as stacks, queues, binary search trees, AVL trees, and algorithms like Dijkstra's and Prim's. Each exercise includes an aim, algorithm, program code in Python, and results confirming successful implementation. The document emphasizes the educational mapping of these exercises to specific program outcomes.
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/ 25

PUCS3TL03

DATA STRUCTURES AND ALGORITHMS


LABORATORY

PRACTICAL EXERCISES
1. Linked list implementation of Stack ADTs.
2. Linked list implementation of Queue ADTs.
3. Implementation of Binary Search Trees
4. Implementation of AVL Trees
5. Implementation of Dijkstra’s Algorithm
6. Implementation of Prim’s Algorithm
7. Implementation of Linear Search and Binary Search. Determine the time required to search
for an element. Repeat the experiment for different values of n, the number of elements in the
list to be searched and plot a graph of the time taken versus n.
8. Implementation of Binary Search. Determine the time required to search for an element.
Repeat the experiment for different values of n, the number of elements in the list to be
searched and plot a graph of the time taken versus n.
9. Implementation of Insertion Sort. Determine the time required to sort the elements.
10. Implementation of Selection Sort. Determine the time required to sort the elements.

30 PERIODS
Ex. No : 1 Date : Linked list implementation of Stack ADTs.

Aim: Write a Python program to insert elements into stack.

Algorithm:

1. A pointer called TOP is used to keep track of the top element in the stack.
2. When initializing the stack, we set its value to -1 so that we can check if the stack is empty by
comparing TOP == -1.
3. On pushing an element, we increase the value of TOP and place the new element in the
position pointed to by TOP.
4. On popping an element, we return the element pointed to by TOP and reduce its value.
5. Before pushing, we check if the stack is already full
6. Before popping, we check if the stack is already empty

Program:

# Stack implementation in python

# Creating a stack
def create_stack():
stack = []
return stack

# Creating an empty stack


def check_empty(stack):
return len(stack) == 0

# Adding items into the stack


def push(stack, item):
stack.append(item)
print("pushed item: " +
item)

# Removing an element from the


stack def pop(stack):
if (check_empty(stack)):
return "stack is
empty"

return stack.pop()

stack = create_stack()
push(stack, str(1))
push(stack, str(2))
push(stack, str(3))
push(stack, str(4))
print("popped item: " + pop(stack))
print("stack after popping an element: " + str(stack))

Output:

Result: Thus the program for implementing stack has been implemented and the output verified successfully.
This experiment mapped with PO1, PO2, PO3, PO5 and PSO1, PSO2 and PSO3.
Ex. No : 2 Date : Linked list implementation of Queue ADTs.

Aim: Write a Python program to implement queue.

Algorithm:

Enqueue Operation

1. check if the queue is full


2. for the first element, set the value of FRONT to 0
3. increase the REAR index by 1
4. add the new element in the position pointed to by

REAR Dequeue Operation

5. check if the queue is empty


6. return the value pointed by FRONT
7. increase the FRONT index by 1
8. for the last element, reset the values of FRONT and REAR to -1

Program:

# Queue implementation in

Python class Queue:

def init (self):


self.queue = []

# Add an element
def enqueue(self, item):
self.queue.append(item)

# Remove an
element def
dequeue(self):
if len(self.queue) <
1: return None
return self.queue.pop(0)

# Display the queue


def display(self):
print(self.queue)

def size(self):
return len(self.queue)
q = Queue()
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
q.enqueue(4)
q.enqueue(5)

q.display()

q.dequeue()

print("After removing an
element") q.display()

Output:

Result: Thus the program for implementing queue has been implemented and the output verified
successfully. This experiment mapped with PO1, PO2, PO3, PO5 and PSO1, PSO2 and PSO3.
Ex. No : 3(a) Implementation Binary Search Tree
Date :

Aim: Write a Python program to insert element into binary tree and display inorder vertical order.

Algorithm:

1. If node == NULL
2. return createNode(data)
3. if (data < node->data)
4. node->left = insert(node->left, data);
5. else if (data > node->data)
6. node->right = insert(node->right, data);
7. return node;

Program:

# Python program to demonstrate


# insert operation in binary search tree

# A utility class that represents


# an individual node in a BST

class Node:
def init (self, key):
self.left = None
self.right = None
self.val = key

# A utility function to insert


# a new node with the given key

def insert(root, key):


if root is None:
return Node(key)
else:
if root.val == key:
return root
elif root.val <
key:
root.right = insert(root.right, key)
else: return root
root.left = insert(root.left, key)

# A utility function to do inorder tree traversal


def inorder(root):
if root:
inorder(root.left)
print(root.val)
inorder(root.right)

# Driver program to test the above


functions # Let us create the following BST
# 50
#/ \
# 30 70
#/\/\
# 20 40 60 80

r = Node(50)
r = insert(r, 30)
r = insert(r, 20)
r = insert(r, 40)
r = insert(r, 70)
r = insert(r, 60)
r = insert(r, 80)

# Print inoder traversal of the BST


inorder(r)

Output:

Result: Thus the program for inserting element in binary tree has been implemented and the output verified
successfully. This experiment mapped with PO1, PO2, PO3, PO5 and PSO1, PSO2 and PSO3.
Ex. No : 3(b) Implementation Binary Search Tree
Date :

Aim: Write a Python program to search element from binary tree.

Algorithm:

1. It checks whether the root is null, which means the tree is empty.
2. If the tree is not empty, it will compare temp? ...
3. Traverse left subtree by calling searchNode() recursively and check whether the value is present in
left subtree.

Program:

#Represent a node of binary tree


class Node:
def init (self,data):
#Assign data to the new node, set left and right children to
None self.data = data;
self.left = None;
self.right =
None;

class
SearchBinaryTree:
def init (self):
#Represent the root of binary
tree self.root = None;
self.flag = False;

#searchNode() will search for the particular node in the binary


tree def searchNode(self, temp, value):
#Check whether tree is
empty if(self.root == None):
print("Tree is empty");

else:
#If value is found in the given binary tree then, set the flag to true
if(temp.data == value):
self.flag =
True; return;

#Search in left subtree


if(self.flag == False and temp.left != None):
self.searchNode(temp.left, value);

#Search in right subtree


if(self.flag == False and temp.right != None):
self.searchNode(temp.right, value);
bt = SearchBinaryTree();
#Add nodes to the binary tree
bt.root = Node(1);
bt.root.left = Node(2);
bt.root.right = Node(3);
bt.root.left.left = Node(4);
bt.root.right.left = Node(5);
bt.root.right.right = Node(6);

print("Search for node 5 in the binary tree")

bt.searchNode(bt.root, 5);
if(bt.flag):
print("Element is present in the binary
tree"); else:
print("Element is not present in the binary tree");

Output:

Result: Thus the program for searching an element in a binary tree has been implemented and the output
verified successfully.

Ex. No : 4 Implementation AVL Tree


Date :
Aim:
To Write a Python program to AVL Tree.

Algorithm:

1. Standard AVL Tree Insertion: class AVLNode: def __init__(self, key): self.key = key. self.left = None.
self.right = None
2. Insertion with Recursive Approach: class AVLTree : def __init__ ( self ): self.root = None. def _height
( self, node ):
3. Insertion with Iterative Approach

Program:
#AVL Tree Code
class TreeNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
self.height = 1

def getHeight(node):
if not node:
return 0
return node.height

def getBalance(node):
if not node:
return 0
return getHeight(node.left) - getHeight(node.right)

def rightRotate(y):
print('Rotate right on node',y.data)
x = y.left
T2 = x.right
x.right = y
y.left = T2
y.height = 1 + max(getHeight(y.left), getHeight(y.right))
x.height = 1 + max(getHeight(x.left), getHeight(x.right))
return x

def leftRotate(x):
print('Rotate left on node',x.data)
y = x.right
T2 = y.left
y.left = x
x.right = T2
x.height = 1 + max(getHeight(x.left), getHeight(x.right))
y.height = 1 + max(getHeight(y.left), getHeight(y.right))
return y
def insert(node, data):
if not node:
return TreeNode(data)

if data < node.data:


node.left = insert(node.left, data)
elif data > node.data:
node.right = insert(node.right, data)

node.height = 1 + max(getHeight(node.left), getHeight(node.right))


balance = getBalance(node)

# Left Left
if balance > 1 and data < node.left.data:
return rightRotate(node)

# Right Right
if balance < -1 and data > node.right.data:
return leftRotate(node)

# Left Right
if balance > 1 and data > node.left.data:
node.left = leftRotate(node.left)
return rightRotate(node)

# Right Left
if balance < -1 and data < node.right.data:
node.right = rightRotate(node.right)
return leftRotate(node)

return node

def inOrderTraversal(node):
if node is None:
return
inOrderTraversal(node.left)
print(node.data, end=", ")
inOrderTraversal(node.right)

# Inserting nodes
root = None
letters = [20,50,10,12,60,40,90,32]
for letter in letters:
root = insert(root, letter)

inOrderTraversal(root)
OUTPUT: #AVL TREE
10, 12, 20, 32, 40, 50, 60, 90

Result:
Ex. No : 5 Implementation of Dijkstra’s Algorithm
Date :

Aim:
To Write a Python program to Implementation of Dijkstra’s Algorithm.

Algorithm:

1. Initialize the graph with the source node to take the value of 0 and all other nodes infinity. Start with the
source as the “current node.”
2. Visit all neighboring nodes of the current node and update their values to the cumulative sum of weights
(distances) from the source. If a neighbor’s current value is smaller than the cumulative sum, it stays the
same. Mark the “current node” as finished.
3. Mark the unfinished minimum-value node as the “current node”.
4. Repeat steps 2 and 3 until all nodes are finished.

Program:

# Python program for Dijkstra's single


# source shortest path algorithm. The program is
# for adjacency matrix representation of the graph
class Graph():

def __init__(self, vertices):


self.V = vertices
self.graph = [[0 for column in range(vertices)]
for row in range(vertices)]

def printSolution(self, dist):


print("Vertex \t Distance from Source")
for node in range(self.V):
print(node, "\t\t", dist[node])

# A utility function to find the vertex with


# minimum distance value, from the set of vertices
# not yet included in shortest path tree
def minDistance(self, dist, sptSet):

# Initialize minimum distance for next node


min = 1e7

# Search not nearest vertex not in the


# shortest path tree
for v in range(self.V):
if dist[v] < min and sptSet[v] == False:
min = dist[v]
min_index = v

return min_index

# Function that implements Dijkstra's single source


# shortest path algorithm for a graph represented
# using adjacency matrix representation
def dijkstra(self, src):

dist = [1e7] * self.V


dist[src] = 0
sptSet = [False] * self.V

for cout in range(self.V):

# Pick the minimum distance vertex from


# the set of vertices not yet processed.
# u is always equal to src in first iteration
u = self.minDistance(dist, sptSet)

# Put the minimum distance vertex in the


# shortest path tree
sptSet[u] = True

# Update dist value of the adjacent vertices


# of the picked vertex only if the current
# distance is greater than new distance and
# the vertex in not in the shortest path tree
for v in range(self.V):
if (self.graph[u][v] > 0 and
sptSet[v] == False and
dist[v] > dist[u] + self.graph[u][v]):
dist[v] = dist[u] + self.graph[u][v]

self.printSolution(dist)

# Driver program
g = Graph(9)
g.graph = [[0, 4, 0, 0, 0, 0, 0, 8, 0],
[4, 0, 8, 0, 0, 0, 0, 11, 0],
[0, 8, 0, 7, 0, 4, 0, 0, 2],
[0, 0, 7, 0, 9, 14, 0, 0, 0],
[0, 0, 0, 9, 0, 10, 0, 0, 0],
[0, 0, 4, 14, 10, 0, 2, 0, 0],
[0, 0, 0, 0, 0, 2, 0, 1, 6],
[8, 11, 0, 0, 0, 0, 1, 0, 7],
[0, 0, 2, 0, 0, 0, 6, 7, 0]
]

g.dijkstra(0)

# This code is contributed by Divyanshu Mehta


RESULT:
Ex.no:6 Implementation of Prim’s Algorithm
import heapq

# This class represents a directed graph using adjacency list representation

class Graph:
def __init__(self, V):
self.V = V
self.adj = [[] for _ in range(V)]

# Function to add an edge to the graph


def add_edge(self, u, v, w):
self.adj[u].append((v, w))
self.adj[v].append((u, w))

# Function to print MST using Prim's algorithm


def prim_mst(self):
pq = [] # Priority queue to store vertices that are being processed
src = 0 # Taking vertex 0 as the source

# Create a list for keys and initialize all keys as infinite (INF)
key = [float('inf')] * self.V

# To store the parent array which, in turn, stores MST


parent = [-1] * self.V

# To keep track of vertices included in MST


in_mst = [False] * self.V

# Insert source itself into the priority queue and initialize its key as 0
heapq.heappush(pq, (0, src))
key[src] = 0

# Loop until the priority queue becomes empty


while pq:
# The first vertex in the pair is the minimum key vertex
# Extract it from the priority queue
# The vertex label is stored in the second of the pair
u = heapq.heappop(pq)[1]

# Different key values for the same vertex may exist in the priority queue.
# The one with the least key value is always processed first.
# Therefore, ignore the rest.
if in_mst[u]:
continue

in_mst[u] = True # Include the vertex in MST

# Iterate through all adjacent vertices of a vertex


for v, weight in self.adj[u]:
# If v is not in MST and the weight of (u, v) is smaller than the current key of v
if not in_mst[v] and key[v] > weight:
# Update the key of v
key[v] = weight
heapq.heappush(pq, (key[v], v))
parent[v] = u
# Print edges of MST using the parent array
for i in range(1, self.V):
print(f"{parent[i]} - {i}")

# Driver program to test methods of the graph class


if __name__ == "__main__":
# Create the graph given in the above figure
V=5
g = Graph(V)

(0, 1, 2), (0, 3, 6), (1, 2, 3), (1, 3, 8), (1, 4, 5), (2, 4, 7), (3, 4, 9)
g.add_edge(0, 1, 2)
g.add_edge(0, 3, 6)
g.add_edge(1, 2, 3)
g.add_edge(1, 3, 8)
g.add_edge(1, 4, 5)
g.add_edge(2, 4, 7)
g.add_edge(3, 4, 9)

g.prim_mst()
Viva - Voice

1) What is data structure?

Data structure refers to the way data is organized and manipulated. It seeks to find ways to make data
access more efficient. When dealing with the data structure, we not only focus onone piece of data but
the different set of data and how they can relate to one another in an organized manner.

2) Differentiate between file and structure storage structure.

The key difference between both the data structure is the memory area that is being accessed. When
dealing with the structure that resides the main memory of the computer system, this is referred to as
storage structure. When dealing with an auxiliary structure, we refer to it as file structures.

3) When is a binary search best applied?

A binary search is an algorithm that is best applied to search a list when the elements are already in
order or sorted. The list is searched starting in the middle, such that if that middle value is not the target
search key, it will check to see if it will continue the search on the lowerhalf of the list or the higher
half. The split and search will then continue in the same manner.

4) What is a linked list?

A linked list is a sequence of nodes in which each node is connected to the node following it.This
forms a chain-like link for data storage.

5) How do you reference all the elements in a one-dimension array?

To reference all the elements in a one -dimension array, you need to use an indexed loop, Sothat, the
counter runs from 0 to the array size minus one. In this manner, You can reference all
the elements in sequence by using the loop counter as the array subscript.

6) In what areas do data structures are applied?

Data structures are essential in almost every aspect where data is involved. In general, algorithms
that involve efficient data structure is applied in the following areas: numericalanalysis,
operating system, A.I., compiler design, database management, graphics, and statistical analysis,
to name a few.

7) What is LIFO?

LIFO is a short form of Last In First Out. It refers how data is accessed, stored and retrieved. Using this
scheme, data that was stored last should be the one to be extracted first. This also means that in order to
gain access to the first data, all the other data that was stored before thisfirst data must first be retrieved
and extracted.
8 ) What is a queue?

A queue is a data structure that can simulate a list or stream of data. In this structure, newelements
are inserted at one end, and existing elements are removed from the other end.

9) What are binary trees?

A binary tree is one type of data structure that has two nodes, a left node, and a right node.
In programming, binary trees are an extension of the linked list structures.

10) Which data structures are applied when dealing with a recursive function?

Recursion is a function that calls itself based on a terminating condition, makes use of the stack. Using
LIFO, a call to a recursive function saves the return address so that it knows howto return to the calling
function after the call terminates.

11) What is a stack?

A stack is a data structure in which only the top element can be accessed. As data is stored inthe stack,
each data is pushed downward, leaving the most recently added data on top.

12) Explain Binary Search Tree

A binary search tree stores data in such a way that they can be retrieved very efficiently. Theleft subtree
contains nodes whose keys are less than the node's key value, while the right subtree contains nodes
whose keys are greater than or equal to the node's key value.
Moreover, both subtrees are also binary search trees.

13) What are multidimensional arrays?


Multidimensional arrays make use of multiple indexes to store data. It is useful when storing data that
cannot be represented using single dimensional indexing, such as data representationin a board game,
tables with data stored in more than one column.

14) Are linked lists considered linear or non-linear data structures?

It depends on where you intend to apply linked lists. If you based it on storage, a linked list is considered
non-linear. On the other hand, if you based it on access strategies, then a linked listis considered linear.

15) How does dynamic memory allocation help in managing data?

Apart from being able to store simple structured data types, dynamic memory allocation can combine
separately allocated structured blocks to form composite structures that expand andcontract as needed.

16) What is FIFO?

FIFO stands for First-in, First-out, and is used to represent how data is accessed in a queue.Data has
been inserted into the queue list the longest is the one that is removed first.
17) What is an ordered list?

An ordered list is a list in which each node's position in the list is determined by the value of itskey
component, so that the key values form an increasing sequence, as the list is traversed.

18) What is merge sort?

Merge sort, is a divide-and-conquer approach for sorting the data. In a sequence of data, adjacent ones
are merged and sorted to create bigger sorted lists. These sorted lists are thenmerged again to form an
even bigger sorted list, which continues until you have one single sorted list.

19) Differentiate NULL and VOID

Null is a value, whereas Void is a data type identifier. A variable that is given a Null
valueindicates an empty value. The void is used to identify pointers as having no initial size.

20) What is the primary advantage of a linked list?

A linked list is an ideal data structure because it can be modified easily. This means that editinga
linked list works regardless of how many elements are in the list.

21) What is the difference between a PUSH and a POP?

Pushing and popping applies to the way data is stored and retrieved in a stack. A push denotes data being
added to it, meaning data is being “pushed” into the stack. On the other hand, a popdenotes data
retrieval, and in particular, refers to the topmost data being accessed.

22) What is a linear search?

A linear search refers to the way a target key is being searched in a sequential data structure. Inthis method,
each element in the list is checked and compared against the target key. The process is repeated until found
or if the end of the file has been reached.

23) How does variable declaration affect memory allocation?

The amount of memory to be allocated or reserved would depend on the data type of the variable being
declared. For example, if a variable is declared to be of integer type, then 32 bitsof memory storage will
be reserved for that variable.

24) What is the advantage of the heap over a stack?

The heap is more flexible than the stack. That's because memory space for the heap can bedynamically
allocated and de-allocated as needed. However, the memory of the heap can at times be slower when
compared to that stack.
25) What is a postfix expression?

A postfix expression is an expression in which each operator follows its operands. The advantage of
this form is that there is no need to group sub-expressions in parentheses or toconsider operator
precedence.

26) What is Data abstraction?

Data abstraction is a powerful tool for breaking down complex data problems into manageable chunks.
This is applied by initially specifying the data objects involved and the operations to be performed on
these data objects without being overly concerned with how the data objects will be represented and
stored in memory.

27) How do you insert a new item in a binary search tree?

Assuming that the data to be inserted is a unique value (that is, not an existing entry in the tree),check first
if the tree is empty. If it's empty, just insert the new item in the root node. If it's not empty, refer to the
new item's key. If it's smaller than the root's key, insert it into the root's left subtree, otherwise, insert it
into the root's right subtree.

28) How does a selection sort work for an array?

The selection sort is a fairly intuitive sorting algorithm, though not necessarily efficient. In thisprocess,
the smallest element is first located and switched with the element at subscript zero,thereby placing the
smallest element in the first position.
The smallest element remaining in the subarray is then located next to subscripts 1 through n-1and
switched with the element at subscript 1, thereby placing the second smallest element in the
second position. The steps are repeated in the same manner till the last element.

29) How do signed and unsigned numbers affect memory?

In the case of signed numbers, the first bit is used to indicate whether positive or negative, which leaves
you with one bit short. With unsigned numbers, you have all bits available for thatnumber. The effect is
best seen in the number range (an unsigned 8-bit number has a range
0-255, while the 8-bit signed number has a range -128 to +127.

30) What is the minimum number of nodes that a binary tree can have?

A binary tree can have a minimum of zero nodes, which occurs when the nodes have
NULLvalues. Furthermore, a binary tree can also have 1 or 2 nodes.

31) What are dynamic data structures?

Dynamic data structures are structures that expand and contract as a program runs. It providesa flexible
means of manipulating data because it can adjust according to the size of the data.
32) In what data structures are pointers applied?

Pointers that are used in linked list have various applications in the data structure. Data structures that
make use of this concept include the Stack, Queue, Linked List and Binary Tree.

33) Do all declaration statements result in a fixed reservation in memory?

Most declarations do, with the exemption of pointers. Pointer declaration does not allocate memory for
data, but for the address of the pointer variable. Actual memory allocation for thedata comes during
run-time.

34) What are ARRAYs?

When dealing with arrays, data is stored and retrieved using an index that refers to the elementnumber in
the data sequence. This means that data can be accessed in any order. In programming, an array is
declared as a variable having a number of indexed elements.

35) What is the minimum number of queues needed when implementing a priority queue?

The minimum number of queues needed in this case is two. One queue is intended for sortingpriorities
while the other queue is used for actual storage of data.

36) Which sorting algorithm is considered the fastest?

There are many types of sorting algorithms: quick sort, bubble sort, balloon sort, radix sort,
merge sort, etc. Not one can be considered the fastest because each algorithm is designed fora particular data
structure and data set. It would depend on the data set that you would want tosort.

37) Differentiate STACK from ARRAY.

Stack follows a LIFO pattern. It means that data access follows a sequence wherein the last data to be
stored when the first one to be extracted. Arrays, on the other hand, does not follow aparticular order
and instead can be accessed by referring to the indexed element within the array.

38) Give a basic algorithm for searching a binary search tree.

1. if the tree is empty, then the target is not in the tree, end search
2. if the tree is not empty, the target is in the tree
3. check if the target is in the root item
4. if a target is not in the root item, check if a target is smaller than the root's value
5. if a target is smaller than the root's value, search the left subtree
6. else, search the right subtree

39) What is a dequeue?

A dequeue is a double-ended queue. This is a structure wherein elements can be inserted orremoved
from either end.
40) What is a bubble sort and how do you perform it?

A bubble sort is one sorting technique that can be applied to data structures such as an array. Itworks
bycomparing adjacent elements and exchanges their values if they are out of order. Thismethod lets
the smaller values “bubble” to the top of the list, while the larger value sinks to the bottom.

41) What are the parts of a linked list?

A linked list typically has two parts: the head and the tail. Between the head and tail lie
theactualnodes. All these nodes are linked sequentially.

42) How does selection sort work?

Selection sort works by picking the smallest number from the list and placing it at the front. Thisprocess is
repeated for the second position towards the end of the list. It is the simplest sort algorithm.

43) What is a graph?

A graph is one type of data structure that contains a set of ordered pairs. These ordered pairs are also
referredto as edges or arcs and are used to connect nodes where data can be storedand retrieved.

44) Differentiate linear from a nonlinear data structure.

The linear data structure is a structure wherein data elements are adjacent to each other. Examples of
linear data structure include arrays, linked lists, stacks, and queues. On the other hand, a non- linear
datastructure is a structure wherein each data element can connect to morethan two adjacent data
elements. Examples of nonlinear data structure include trees and graphs.

45) What is an AVL tree?

An AVL tree is a type of binary search tree that is always in a state of partially balanced. The balance
ismeasured as a difference between the heights of the subtrees from the root. This self-balancing tree
wasknown to be the first data structure to be designed as such.

46) What are doubly linked lists?

Doubly linked lists are a special type of linked list wherein traversal across the data elements can be
done in both directions. This is made possible by having two links in every node, one that links to the
next node and another one that connects to the previous node.

47) What is Huffman's algorithm?

Huffman's algorithm is used for creating extended binary trees that have minimum weightedpath
lengths from the given weights. It makes use of a table that contains the frequency of occurrence
foreach data element.
48) What is Fibonacci search?

Fibonacci search is a search algorithm that applies to a sorted array. It makes use of a divide- and-
conquerapproach that can significantly reduce the time needed in order to reach the targetelement.

49) Briefly explain recursive algorithm.

Recursive algorithm targets a problem by dividing it into smaller, manageable sub-problems. The
output of one recursion after processing one sub-problem becomes the input to the next recursive
process.

50) How do you search for a target key in a linked list?

To find the target key in a linked list, you have to apply sequential search. Each node is traversed
andcompared with the target key, and if it is different, then it follows the link to thenext node.
This traversal continues until either the target key is found or if the last node is reached.

You might also like