Dsa Material QB QP
Dsa Material QB QP
By
Mr. Radhakrishnan.P, M.Tech,M.C.A,M.B.A(HR),M.Sc(Psy),B.Lit(Tamil), M.A(Criminology),(Ph.D).
Assistant Professor
School of CS & AI
SR University
SYLLABUS
DATA STRUCTURES AND ALGORITHMS
UNIT I
Basic concepts - Data types, Abstract Data Types, Data structures, Algorithms.
Searching- Linear Search, Binary Search
Sorting- Bubble Sort, Insertion Sort, Selection Sort, Quick sort, Merge sort, Comparison of Sorting methods.
UNIT II
Linear Data Structures Part 1:
Stack ADT - Definitions, operations, array and linked implementations, applications-infix to postfix conversion,
recursion implementation,
Queue ADT - Definitions and operations, array and linked Implementations, Applications of Queue Circular queues
and operations
UNIT III
Linear Data Structures Part 2:
Linear Lists, Sequential and Linked allocation, list ADT, array and linked Implementations, Singly Linked Lists-
Operations-Insertion, Deletion, Doubly Linked Lists-Operations - Insertion, Deletion.
UNIT IV
Non Linear Data Structures Part 1:Trees - Basic Terminology, Binary tree ADT, array and linked
representations, traversals, threaded binary trees, Priority Queues-Definition, ADT, Realizing a Priority Queue using
Heap.
Search Trees: Binary Search Trees, Definition, ADT, Implementation, Operations- Searching, Insertion and
Deletion.
Balanced Search Trees: AVL Trees - Definition, Operations – Insertion and Searching.
B-Trees - Definition, B-Tree of order m, operations - insertion and deletion. Introduction to Red-Black and Splay
Trees, Comparison of Search Trees.
UNIT V
TEXT BOOKS:
rd
1. Mark Allen Weiss, “Data structures and Algorithm Analysis”, 3 edition, Pearson Education. Ltd.,
2. S.Sahani, “Data structures, Algorithms and Applications”, Universities Press.
REFERENCE BOOKS:
1. Michael T.Goodrich, R.Tamassia and D.Mount, “Data structures and Algorithms”, Wiley student edition,
seventh edition, John Wiley and Sons.
2. Adam Drozdek, “Data structures and algorithms”, 3rd Edition, Cengage Learning.
3. Langsam, Augenstein and Tanenbaum, “Data structures using C”, PHI.
4. G.L.Heileman, “Data structures, algorithms and OOP”, TMH edition
Unit - 1 Data Structures and Algorithms
UNIT I
Basic concepts - Data types, Abstract Data Types, Data structures, Algorithms.
Searching- Linear Search, Binary Search
Sorting- Bubble Sort, Insertion Sort, Selection Sort, Quick sort, Merge sort, Comparison of
Sorting methods.
Data Structures
Data may be organized in many different ways logical or mathematical model of a program
particularly organization of data. This organized data is called “Data Structure”.
Or
The organized collection of data is called a ‘Data Structure’.
Data Types
Primitive Data types are directly supported by the language (ie) any operation is directly
performed in these data items.
o Ex: integer, Character, Real numbers etc.
Non-primitive data types are not defined by the programming language, but are instead
created by the programmer.
1. Linear data structures organize their data elements in a linear fashion, where data
elements are attached one after the other. Linear data structures are very easy to
implement, since the memory of the computer is also organized in a linear fashion.
Some commonly used linear data structures are arrays, linked lists, stacks and
queues.
2. In nonlinear data structures, data elements are not organized in a sequential fashion.
Data structures like multidimensional arrays, trees, graphs, tables and sets are some
examples of widely used nonlinear data structures.
Algorithm
Definition: -
An algorithm is a Step By Step process to solve a problem, where each step indicates an
intermediate task. Algorithm contains finite number of steps that leads to the solution of the
problem.
Categories of Algorithm:
Based on the different types of steps in an Algorithm, it can be divided into three categories,
namely
Sequence
Selection and
Iteration
Sequence:
The steps described in an algorithm are performed successively one by one without
skipping any step.
The sequence of steps defined in an algorithm should be simple and easy to understand.
Each instruction of such an algorithm is executed, because no selection procedure or
conditional branching exists in a sequence algorithm.
Example:
// adding two numbers
Step 1: start
Step 2: read a,b
Step 3: Sum=a+b
Step 4: write Sum
Step 5: stop
Selection:
The sequence type of algorithms are not sufficient to solve the problems, which involves decision
and conditions. In order to solve the problem which involve decision making or option selection,
we go for Selection type of algorithm.
The general format of Selection type of statement is as shown below:
if(condition)
Statement-1;
else
Statement-2;
The above syntax specifies that if the condition is true, statement-1 will be executed otherwise
statement-2 will be executed. In case the operation is unsuccessful.
Then sequence of algorithm should be changed/ corrected in such a way that the system will re-
execute until the operation is successful.
Iteration: Iteration type algorithms are used in solving the problems which involves
repetition of statement.
In this type of algorithms, a particular number of statements are repeated ‘n’ no. of times.
Example:
Step 1 : start
Step 2 : read n
Step 3 : repeat
step 4 : until n>0
(a) r=n mod 10
(b) s=s+r
(c) n=n/10
Step 5 : write s
Step 6 : stop
1.Linear Search
• Linear search, the simplest search algorithm, is mainly used to find the element from
an unordered list.
• It is also known by another name called sequential search algorithm. In linear search,
the list is simply traversed, and each element in the list is matched with the element whose
location needs to be found.
• When the searching process is done, it returns the location of the element, else the
algorithm returns NULL.
for(i=0;i<size;i++)
{
if(search==a[i])
{
flag=1;
break;
}
}
if (flag==1)
printf("%d fount at the position %d ",search,mid+1);
else
printf("element not found");
return 0;
}
Advantages:
It is simplest known technique.
The elements in the list can be in any order.
Disadvantages:
This method is in efficient when large numbers of elements are present in list because time
taken for searching is more.
Complexity of Linear Search: The worst and average case complexity of Linear search is
O(n), where ‘n’ is the total number of elements present in the list.
Binary Search
Binary Search is one of the fastest searching algorithms.
It is used for finding the location of an element in a linear array.
It works on the principle of divide and conquer technique.
Binary Search Algorithm can be applied only on Sorted arrays.(Ascending Order)
So, the elements must be arranged in Either ascending order if the elements are numbers Or
dictionary order if the elements are strings.
To apply binary search on an unsorted array,First, sort the array using some sorting
technique.Then, use binary search algorithm.
start=0;
stop=size-1;
while(start<=stop)
{
mid=(start+stop)/2;
if(search==a[mid])
{
flag=1;
break;
}
else if (search<a[mid])
stop=mid-1;
else
start=mid+1;
}
if(flag==1)
printf("%d fount at the position %d ",search,mid+1);
else
printf("element not found");
return 0;
}
Types of Sorting
1.Bubble Sort
2.Selection Sort
3.Insertion Sort
4.Merge Sort
5.Quick Sort
1.BUBBLE SORT
Bubble sort is a sorting algorithm that compares two adjacent elements and swaps them until
they are in the intended order.
Just like the movement of air bubbles in the water that rise up to the surface, each element of
the array move to the end in each iteration.
Therefore, it is called a bubble sort.
Algorithm :
Step 0 : Initialize n to length of the array
Step 1 : Initialize j to 0 and compare a[j] with a[j+1] (compare adjacent elements starting
from 0th index)
Step 2 : if a[j] > a[j+1] swap a[j] and a[j+1]
Step 3 : repeat steps 1 and 2 until j reached end of the array ( by end of this one element will
be placed at its correct order )
Step 4 : continue from Step 1 n-1 times ( so that all elements will be in proper order)
Example:
printf("Values are");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1-i;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("Ascending Order Using Bubble Sort \n");
for(i=0;i<n;i++)
printf("\t %d",a[i]);
return 0;
}
OUTPUT
printf("Enter Values");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
INSERTION SORT
Insertion sort is a sorting algorithm that places an unsorted element at its suitable place in
each iteration.
Insertion sort is a simple sorting algorithm that works similar to the way you sort playing
cards in your hands
Advantage
o Simple implementation
o Efficient for small data sets
o Adaptive, i.e., it is appropriate for data sets that are already substantially sorted.
Algorithm
Step 1 - If the element is the first element, assume that it is already sorted. Return 1.
Step 2 - Pick the next element, and store it separately in a key.
Step 3 - Now, compare the key with all elements in the sorted array.
Step 4 - If the element in the sorted array is smaller than the current element, then move to
the next element. Else, shift greater elements in the array towards the right.
Step 5 - Insert the value.
Step 6 - Repeat until the array is sorted.
EXAMPLE :
return 0;
}
OUTPUT
Enter the total Number of Elements : 5
Enter the Array Elements : 25
6
97
-1
15
Insertion Sort Result : -1 6 15 25 97
***********
MERGE SORT
Merge Sort is one of the most popular sorting algorithms that is based on the principle
of Divide and Conquer Algorithm.
Here, a problem is divided into multiple sub-problems.
Each sub-problem is solved individually.
Finally, sub-problems are combined to form the final solution.
Algorithm:
step 1: start
step 2: declare array and left, right, mid variable
step 3: perform merge function.
if left > right
return
mid= (left+right)/2
mergesort(array, left, mid)
mergesort(array, mid+1, right)
merge(array, left, mid, right)
step 4: Stop
Follow the steps below the solve the problem:
MergeSort(arr[], l, r)
If r > l
Find the middle point to divide the array into two halves:
middle m = l + (r – l)/2
Call mergeSort for first half:
Call mergeSort(arr, l, m)
Call mergeSort for second half:
Call mergeSort(arr, m + 1, r)
Merge the two halves sorted in steps 2 and 3:
Call merge(arr, l, m, r)
int main()
{
int a[50],i,j,size,temp,low,high,mid,mi,k;
partition(a,0,size-1);
return 0;
}
while(lower<=mid&&mi<=high)
{
if(a[lower]<=a[mi])
{
temp[i]=a[lower];
lower++;
}
else
{
temp[i]=a[mi];
mi++;
}
i++;
}
if(lower>mid)
{
for(k=mi;k<=high;k++)
{
temp[i]=a[k];
i++;
}
}
else
{
for(k=lower;k<=mid;k++)
{
temp[i]=a[k];
i++;
}
}
for(k=low;k<=high;k++)
{
a[k]=temp[k];
}
}
OUTPUT :
EXAMPLE
if(first<last)
{
pivot=first;
i=first;
j=last;
while(i<j)
{
while(a[i]<=a[pivot] && i<last)
i++;
while(a[j]>a[pivot])
j--;
if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
temp=a[pivot];
a[pivot]=a[j];
a[j]=temp;
quicksort(a,first,j-1);
quicksort(a,j+1,last);
}
}
int main()
{
int i, n, a[25];
quicksort(a,0,n-1);
OUTPUT
Enter the total Number of Elements : 5
Enter elements: 12 5 47 11 1
Order of Sorted elements: 1 5 11 12 47
Comparison of Sorting
**************
UNIT II
Linear Data Structures Part 1:
Stack ADT - Definitions, operations, array and linked implementations, applications-infix to
postfix conversion, recursion implementation,
Queue ADT - Definitions and operations, array and linked Implementations, Applications of
Queue Circular queues and operations
Stack
Stack is a linear DS.
LIFO or FILO
Insertion and deletion can be done at only one end of the stack called top of the stack.
Top position :-
It is always point to the last element inserted in the stack.
For empty stack , top position value is -1.
Application of stack:
Operation
1. PUSH
2. POP
3. PEEK
1.push () operation
int push(int value)
{
if(top == SIZE-1)
printf("\nStack is Full");
else
{
top++;
stack[top] = value;
printf("\nInsertion success");
}
}
2.Pop() operation
int pop()
{
if(top == -1)
printf("\nStack is Underflow");
else
{
printf("\nDeleted : %d", stack[top]);
top--;
}
}
3.Peek() operation
int peek()
{
if(top == -1)
printf("\nStack is Underflow");
else
printf("\n Peek of Stack : %d", stack[top]);
}
4.Traverse
int display()
{
if(top == -1)
printf("\nStack is Underflow");
else
{
int i;
printf("\nStack elements are:\n");
for(i=top; i>=0; i--)
printf("%d\n",stack[i]);
}
}
Example 2:
Infix notation => A + B - C
Example 3:
Infix notation => A + B * C
-----------------------------------------
QUEUE
Queues are first-in-first-out (FIFO) structures – The first element added to a queue is the
first to be removed and the last element to be added to a queue will be the last to be
removed.
Operation
1. Enqueue (Insertion ) – rear end
2. Dequeue(Deletion) – front end
#define SIZE 5
int queue[SIZE],front=0,rear=0,i;
1.enqueue operation
int enqueue()
{
if(rear==SIZE)
printf("\n Queue is Full");
else
{
printf("\n Enter number:");
scanf("%d",&queue[rear++]);
}
}
2.dequeue operation
int dequeue()
{
if(front==rear)
printf("\n Queue is empty");
else
printf("\n Deleted Element is %d",queue[front++]);
}
3.Traverse
int display()
{
if(front==rear)
printf("\n Queue is Empty");
else
{
printf("\n Queue Elements are:\n ");
for(i=front; i<rear; i++)
printf("%d \t",queue[i]);
}
}
-----------------------------------------
Circular Queue Using Array Implementation
In a Linear queue, once the queue is completely full, it's not possible to insert any
more elements. When we dequeue any element to remove it from the queue, we are
actually moving the front of the queue forward, but rear is still pointing to the last
element of the queue, we cannot insert new elements.
Circular Queue is also a linear data structure, which follows the principle of
FIFO(First In First Out), but instead of ending the queue at the last position, it again
starts from the first position after the last, hence making the queue behave like a
circular data structure.
1) Enqueue () Opeartion :
void enqueue()
{
int elt;
if( ((rear+1)%SIZE)==front)
{
printf("\n Circular Queue is full… insertion not possible...");
return;
}
cqueue[rear]=elt;
2 ) Dequeue operation
void dequeue()
{
if(front==-1 && rear==-1)
{
printf("\n Circular Queue is empty...");
return;
}
printf("Deleted Element is : %d",cqueue[front]);
if(front==rear)
front=rear=-1;
else
front=(front+1)%SIZE;
}
Applications of Queue:
1. Queues are widely used as waiting lists for a single shared resource like printer, disk,
CPU.
2. Queues are used as buffers on MP3 players and portable CD players, iPod playlist.
Example :
------------------------------------
Recursion
A function that calls itself is known as a recursive function.
Types of recursion in C
There are two types of recursion present in the C programming language.
Direct Recursion
Indirect Recursion
1. Direct Recursion in C
If a function calls itself directly then the function is known as direct recursive function.
Example:
int fib(int num)
{
if (num==1 || num==2)
return 1;
else
return (fib(num-1)+fib(num-2));
}
In the above example, fib() function is direct recursive. Because the statements inside the
fib() function calls the fib() function directly.
2. Indirect Recursion in C
A function that does not call itself directly then function is known as an indirect recursive
function.
Example
int first_function(int num)
{
if (num<=2)
return 2;
else
return new_function(num);
}
int new_function(int num)
{
return first_function(num);
}
In the above example, first_function() calls the new_function(), which is indeed a new
function. Then this new_function() calls the first_function(). So, it is an indirect recursive
function.
EXAMPLE:
Tower of Hanoi
These rings are of different sizes and stacked upon in an ascending order, i.e. the
smaller one sits over the larger one.
It is a mathematical game or puzzle that consists of three rods with ’n’ number of
disks of different diameters.
The objective of the game is to shift the entire stack of disks from one rod to another
rod following these three rules :
1. Only one disk can be moved at a time.
2. Only the uppermost disk from one stack can be moved on to the top of
another stack or an empty rod.
3. Larger disks cannot be placed on the top of smaller disks.
The minimal number of moves required to solve the Tower of Hanoi puzzle of n disks would be (2^n) − 1.
START
IF disk == 1, THEN
move disk from source to dest
ELSE
Hanoi(disk - 1, source, aux, dest) // Step 1
move disk from source to dest // Step 2
Hanoi(disk - 1, aux, dest, source) // Step 3
END IF
****************
Linked Representation of Stacks:
The drawback in that the array must be declared to have some fixed size. In case the
stack is a very small one or its maximum size is known in advance
In
a linked stack, every node has two parts, one that stores data and another that stores
the address of the next node. The START pointer of the linked list is used as TOP.
All insertions and deletions are done at the TOP (similar to insertion at beginning).
If TOP = NULL, then it indicates that the stack is empty.
Applications of Stacks
✔ Stack is used to reversing the given string.
✔ Stack is used to evaluate a postfix expression.
✔ Stack is used to convert an infix expression into postfix/prefix form.
✔ Stack is used to matching the parentheses in an expression.
1. Push Function
void push(int elt)
{
struct node *n;
n=(struct node*)malloc(sizeof(struct node));
n->data=elt;
n->next=top;
top=n;
printf("\n Insertion is sucessful");
}
2. Pop Function
void pop()
{
struct node *temp;
temp=top;
if(top==NULL)
printf("Stack Underflow");
else
{
printf("Pop out element is %d",top->data);
top=top->next;
free(temp);
}
}
3. Peek Function
void peek()
{
if (top == NULL)
printf("\n Stack is empty");
else
printf("\n Top of the Stack %d ", top->data);
}
while(temp!=NULL)
{
printf("\t %d",temp->data);
temp=temp->next;
}
}
}
------------------------------------------
Queue Linked List Representation
ARRAYs: Queues can be easily represented using linear arrays. Every queue has front and
rear variables that point to the position from where deletions and insertions can be done,
respectively. The array representation of a queue is shown below.
Drawback: The array must be declared to have some fixed size. If we allocate space for 50
elements in the queue and it hardly uses 20–25 locations, then half of the space will be
wasted.
Array Representation:
Drawback: If we implement the queue using an array, we need to specify the array size
at the beginning (at compile time). We can't change the size of an array at runtime. So,
the queue will only work for a fixed number of elements.
In a linked queue, each node of the queue consists of two parts i.e. data part and the
next part. Each element of the queue points to its immediate next element in the
memory.
In the linked queue, there are two pointers maintained in the memory i.e. front
pointer and rear pointer. The front pointer contains the address of the starting
element of the queue while the rear pointer contains the address of the last element of
the queue.
1. Enqueue Function
void enqueue(int elt)
{
n=(struct node*)malloc(sizeof(struct node));
n->data=elt;
n->next=NULL;
if (front==NULL && rear==NULL)
front=rear=n;
else
{
rear->next=n;
rear=n;
}
printf("\n Insertion is sucessful");
}
2. Dequeue Function
void dequeue()
{
if(front==NULL && rear==NULL)
printf("Stack Underflow");
else
{
temp=front;
front=front->next;
if(front==NULL)
rear=NULL;
free(temp);
}
printf("Enqueue element sucessfully");
}
Sequential Allocation
Sequential allocation refers to the arrays or a contiguous block of memory.
It is hard to Insert and delete files and requires movement to do so.
Space is wasted.
Expensive.
It requires less space as only information is stored.
It cannot be extended or reduced as per the requirements.
Similar amount of time is required to access every element.
Elements are stored in consecutive memory locations.
A direct route is present to reach element individually.
List ADT
A list is a ordered tuple of homogeneous elements
A0, A1, A2, …., An-1
where Ai is the i-th element of the list
The position of element Ai is i; positions range from 0 to n-1 inclusive
The size of a list is N (a list with no elements is called an “empty list”.
One-Dimensional Arrays:
A list of items can be given one variable name using only one subscript and such a variable
is called single-subscripted variable or one dimensional array. A one dimensional array can
be declared as follows:
10 20 30 40 50 60 70
10 20 30 40 50 60 70
Index 0 1 2 3 4 5 6
10 20 30 40 Null
Basic Operations:
1. Insertion
a. At first
b. At last
c. At a given location or given data item (At middle)
2. Deletion
a. First Node
b. Last Node
c. Node in given location or given data item
Initial Condition
HEAD or START = NULL;
Address of the first node in the list is stored in HEAD/START. Initially there is no node in the
list. So, HEAD/START is initialized to NULL (No address).
Insertion Operation
1. Insertion At First
void insert_at_beg()
{
newnode=(struct node *)malloc(sizeof(struct node));
printf("\n Enter the data to insert at begin: ");
scanf("%d",&newnode->data);
newnode->next=NULL;
if(start==NULL)
start=newnode;
else
{
newnode->next=start;
Deletion Operation
1. Delete At First
void del_at_beg()
{
temp=start;
start=start->next; /*First element deleted*/
free(temp);
}
2. Delete At Mid
void del_at_mid()
{
int key;
printf("\n Enter element to delete..");
scanf("%d",&key);
p=start;
while(p->next!= NULL)
{
if(p->next->data==key) /*Element deleted in between*/
{
temp=p->next;
p->next=temp->next;
free(temp);
}
p=p->next;
}
}
3. Delete At End
void del_at_end()
{
temp=start;
while(temp->next!= NULL)
{
p=temp;
temp=temp->next;
}
free(p->next);
p->next=NULL;
}
10 20 30 40
****************
Doubly-Linked List
A more sophisticated kind of linked list is a doubly-linked list or two-way linked list,
in which each node has two links: one points to the previous node, or points to a null value or
empty list if it is the first node; and one points to the next, or points to a null value or empty list
if it is the final node.
*prev data *next
Null 15 56 27 Null
First Node Last Node
Figure : Doubly Linked List
Basic Operations:
1. Insertion
a. At first
b. At last
c. At a given location or given data item (At middle)
2. Deletion
a. First Node
b. Last Node
c. Node in given location or given data item
Insertion Operation
1. Insertion At First
void insert_at_beg()
{
newnode=(struct node *)malloc(sizeof(struct node));
printf("\nEnter the data to insert at begin: ");
scanf("%d",&newnode->data);
newnode->next=NULL;
newnode->prev=NULL;
if(start==NULL)
start=newnode;
2. Insertion At Mid
void insert_mid()
{
int key;
newnode=(struct node *)malloc(sizeof(struct node));
printf("\nEnter the data to insert at middle: ");
scanf("%d",&newnode->data);
newnode->next=NULL;
newnode->prev=NULL;
if(start==NULL)
start=temp=newnode;
else
{
printf("\nEnter the element after which you want to insert: ");
scanf("%d",&key);
temp=start;
do
{
if(temp->data==key)
{
newnode->next=temp->next;
temp->next->prev=newnode;
temp->next=newnode;
newnode->prev=temp;
return;
}
else
temp=temp->next;
}while(temp!=NULL);
}
}
3. Delete At End
void del_at_end()
{
temp=start;
while(temp->next!= NULL)
{
p=temp;
temp=temp->next;
} /*Last element deleted*/
free(temp);
p->next=NULL;
}
Doubly-circular-linked list
In a doubly-circular-linked list, each node has two links, similar to a doubly-linked
list, except that the previous link of the first node points to the last node and the next link of
the last node points to the first node. As in doubly-linked lists, insertions and removals can be
done at any point with access to any nearby node.
5 10 15 20
***********************
UNIT IV
Non Linear data structures: Trees – Basic Terminology, Binary tree ADT, array and linked
representations, traversals, threaded binary trees, Priority Queues-Definition, ADT, Realizing a
Priority Queue using Heap.
Search Trees-Binary Search Trees, Definition, ADT, Implementation, Operations- Searching,
Insertion and Deletion, AVL Trees - Definition, Operations – Insertion and Searching,
B-Trees - Definition, B-Tree of order m, operations - insertion and deletion, Introduction to Red-
Black and Splay Trees, Comparison of Search Trees.
Tree
In linear data structure, data is organized in sequential order and in non-linear data
structure; data is organized in random order.
Example
Tree Terminology
1. Root
In a tree data structure, the first node is called as Root Node.
We can say that root node is the origin of tree data structure.
In any tree, there must be only one root node. We never have multiple root nodes in a tree.
2. Edge
In a tree data structure, the connecting link between any two nodes is called as EDGE.
In a tree with 'N' number of nodes there will be a maximum of 'N-1' number of edges.
3. Parent
In a tree data structure, the node which is predecessor of any node is called as PARENT
NODE.
In simple words, the node which has branch from it to any other node is called as parent
node.
Parent node can also be defined as "The node which has child / children".
4. Child
In a tree data structure, the node which is descendant of any node is called as CHILD
Node.
In simple words, the node which has a link from its parent node is called as child node.
5. Siblings
In a tree data structure, nodes which belong to same Parent are called as SIBLINGS.
In simple words, the nodes with same parent are called as Sibling nodes.
6. Leaf
In a tree data structure, the node which does not have a child is called as LEAF Node.
In simple words, a leaf is a node with no child.
In a tree data structure, the leaf nodes are also called as External Nodes.
In a tree, leaf node is also called as 'Terminal' node.
7. Internal Nodes
In a tree data structure, the node which has at least one child is called as INTERNAL
Node.
In simple words, an internal node is a node with at least one child.
Internal nodes are also called as 'Non-Terminal' nodes.
8. Degree
In a tree data structure, the total number of children of a node is called as DEGREE of that
Node.
In simple words, the Degree of a node is total number of children it has.
The highest degree of a node among all the nodes in a tree is called as 'Degree of Tree'
9. Level
In a tree data structure, the root node is said to be at Level 0 and the children of root node
are at Level 1 and the children of the nodes which are at Level 1 will be at Level 2 and so
on...
In simple words, in a tree each step from top to bottom is called as a Level and the
Level count starts with '0' and incremented by one at each level (Step).
10. Height
In a tree data structure, the total number of edges from leaf node to a particular node
in the longest path is called as HEIGHT of that Node.
In a tree, height of all leaf nodes is '0'.
11. Depth
In a tree data structure, the total number of edges from root node to a particular
node is called as DEPTH of that Node.
In simple words, the highest depth of any leaf node in a tree is said to be depth of that tree.
In a tree, depth of the root node is '0'.
In a tree, the total number of edges from root node to a leaf node in the longest path is said to be
Depth of the tree.
12. Path
In a tree data structure, the sequence of Nodes and Edges from one node to another
node is called as PATH between two Nodes.
Length of a Path is total number of nodes in that path.
In below example the path A - B - E - J has length 4.
**************************
Types of Trees
1. Binary Tree
2. Binary Search Tree
3. AVL Tree
4. B-Tree etc.,
1.Binary Tree
In a normal tree, every node can have any number of children.
Binary tree is a special type of tree data structure in which every node can have a
maximum of 2 children.
One is known as left child and the other is known as right child.
A tree in which every node can have a maximum of two children is called as Binary Tree.
In a binary tree, every node can have either 0 children or 1 child or 2 children but not more
than 2 children.
Example
Strictly binary tree is also called as Full Binary Tree or Proper Binary Tree or 2-Tree
A binary tree in which every internal node has exactly two children and all leaf nodes
are at same level is called Complete Binary Tree.
But in strictly binary tree, every node should have exactly two children or none and in
complete binary tree all the nodes must have exactly two children and at every level of
complete binary tree there must be 2level number of nodes.
For example at level 2 there must be 22 = 4 nodes and at level 3 there must be 23 = 8 nodes.
An almost complete binary tree is a binary tree that satisfies the following 2 properties-
All the levels are completely filled except possibly the last level.
The last level must be strictly filled from left to right.
Example
A binary tree can be converted into Full Binary tree by adding dummy nodes to
existing nodes wherever required.
The full binary tree obtained by adding dummy nodes to a binary tree is called as
Extended Binary Tree
In above figure, a normal binary tree is converted into full binary tree by adding dummy nodes (In
pink color).
**************************
1. Array Representation
In array representation of binary tree, we use a one dimensional array (1-D Array) to
represent binary tree.Consider the above example of binary tree and it is represented as
follows...
To represent a binary tree of depth 'n' using array representation, we need one dimensional array
with a maximum size of 2n+1 - 1.
The above example of binary tree represented using Linked list representation is shown as
follows...
struct node
{
int data;
struct node* left;
struct node* right;
}*node,*root;
// Creation
/* newnode() allocates a newnode with the given data and NULL left & right pointers. */
/* Display */
int main()
{
/*create root*/
root = newnode(1);
root->left = newnode(2);
root->right = newnode(3);
/* 2 and 3 become left and right children
of 1
1
/ \
2 3
/ \ / \
NULL NULL NULL NULL
*/
root->left->left = newnode(4);
/* 4 becomes left child of 2
1
/ \
2 3
/ \ / \
4 NULL NULL NULL
/\
NULL NULL
*/
inorder(root);
return 0;
}
OUTPUT
4 ->2 ->1 ->3 ->
***************************
Binary Tree Traversals
When we wanted to display a binary tree, we need to follow some order in which all the
nodes of that binary tree must be displayed.
Displaying (or) visiting order of nodes in a binary tree is called as Binary Tree
Traversal.
Preorder Traversal: A - B - D - I - J - F - C - G - K – H
In order Traversal : I - D - J - B - F - A - G - K - C - H
Post order Traversal: I - J - D - F - B - K - G - H - C - A
*********************
Threaded Binary Tree
In threaded binary tree, NULL pointers are replaced by references to other nodes in the
tree, called threads.
Definition:
Example for General Binary Tree Example for Threaded Binary Tree
Advantage:-
1. By doing threading we avoid the recursive method of traversing a tree , which doesn’t use
of stack and consumes a lot of memory and time.
2. The node can keep record of its root.
3. Backward Traverse is possible.
4. Applicable in most types of the binary tree.
Disadvantage:-
1. Tree traversal algorithm becomes complex.
2. Extra space needed to store boolean values.
3. Inseration and deletion operation becomes more difficult.
*******************************
Priority Queue
Priority Queue is an extension of the queue with the following properties:
1. Every item has a priority associated with it.
2. An element with high priority is dequeued before an element with low priority.
3. If two elements have the same priority, they are served according to their order in the
queue.
Heaps:
A heap is a specific tree based data structure in which all the nodes of tree are in a specific
order. Let’s say if X is a parent node of Y, then the value of X follows some specific order with
respect to value of Y and the same order will be followed across the tree.
Binary Heap
A binary heap is a type of binary tree (but not a binary search tree) that has the following
properties:
1. Shape: It is a complete tree. (Remember that a complete binary tree is one where every
level except the last one is completely filled, and the last level has all leaves as far left
as possible.)
2. Order (heap): The parent of a node is ≥ all of its children (for a max heap) or ≤ all of
its children (for a min heap).
There can be two types of binary heap:
Max Heap: In this type of heap, the value of parent node will always be greater than or
equal to the value of child node across the tree and the node with highest value will be the root
node of the tree.
Min Heap: In this type of heap, the value of parent node will always be smaller than or
equal to the value of child node across the tree and the node with smallest value will be the root
node of the tree.
2.Deleting
Remove min: The minimum value is stored at the root of the tree. But the root of the
tree cannot be directly removed. First, it is replaced with any one of the leaves and then
removed.
Step 1 Step 2
Step 3 Step 4
Steps
If there is no node,
Unable to delete.
Else (a node is already present)
Remove or delete the root node , replace with lastLeafNode.
heapify the node
Priority Queue Applications
Dijkstra's algorithm
for load balancing and interrupt handling in an operating system
for data compression in Huffman code
************************
Application of BST
C implementation (insert)
struct node* insert(struct node *node, int data)
{
if (node == NULL)
return newnode(data);
if (data < node->data)
node->left = insert(node->left,data);
else if (data > node->data)
node->right = insert(node->right,data);
return node;
}
C implementation (Search)
struct node* search(struct node *node, int s)
{
if(node==NULL || node->data==s)
return node;
else if(s > node->data)
return search(node->right,s);
else
return search(node->left,s);
}
C implementation (deletion)
struct node* del(struct node *node, int x)
{
if(node==NULL)
return NULL;
if(x>node->data)
node->right= del(node->right, x);
else if(x<node->data)
node->left = del(node->left, x);
else
{
//No Children
if(node->left==NULL && node->right==NULL)
{
free(node);
return NULL;
}
//One Child
else if(node->left==NULL || node->right==NULL)
{
if(node->left==NULL)
temp = node->right;
else
temp = node->left;
free(node);
return temp;
}
//Two Children
else
{
temp = findmin(node->right);
node->data = temp->data;
node->right = del(node->right, temp->data);
}
}
return node;
}
Example (BST)
Construct a Binary Search Tree by inserting the following sequence of numbers...
10,12,5,4,20,8,7,15 and 13
Above elements are inserted into a Binary Search Tree as follows...
*****************************
AVL TREE
AVL tree is a self-balanced binary search tree.
A binary tree is said to be balanced, if the difference between the heights of left and right
subtrees of every node in the tree is either -1, 0 or 1.
In an AVL tree, every node maintains a extra information known as balance factor.
The AVL tree was introduced in the year of 1962 by G.M. Adelson-Velsky and
E.M.Landis.
Definition
An AVL tree is a balanced binary search tree. In an AVL tree, balance factor of every node
is either 1, 0 or 1.
Balance factor = height Of Left Subtree – height Of Right Subtree
The above tree is a binary search tree and every node is satisfying balance factor condition. So this
tree is said to be an AVL tree.
Every AVL Tree is a binary search tree but all the Binary Search Trees need not to be AVL
trees.
AVL Rotations
Single Rotation
1) LL Rotation
2) RR Rotation
Double Rotation
3) LR Rotation
4) RL Rotation
LL Rotation( Right Side Rotation)
A node has been We first perform the Node C is still We shall now right-rotate The tree is now
inserted into the left rotation on the left unbalanced, however the tree, making B the new balanced.
right subtree of the subtree of C. This now, it is because of the root node of this subtree. C
left subtree. This makes A, the left left-subtree of the left- now becomes the right
makes C an subtree of B. subtree. subtree of its own left
unbalanced node. subtree.
These scenarios cause
AVL tree to perform
left-right rotation.
Right-Left Rotation
A node has been First, we perform the Node A is still A left rotation is The tree is now balanced.
inserted into the right rotation along C unbalanced because of performed by making B
left subtree of the node, making C the right the right subtree of its the new root node of the
right subtree. subtree of its own left right subtree and subtree. A becomes the
This makes A, an subtree B. Now, B requires a left rotation. left subtree of its right
unbalanced node becomes the right subtree B.
with balance subtree of A.
factor 2.
if(x>T->data)
{
T->right=insert(T->right,x);
if(BF(T)==-2)
if(x>T->right->data)
T=RR(T);
else
T=RL(T);
}
else
if(x<T->data)
{
T->left=insert(T->left,x);
if(BF(T)==2)
if(x<T->left->data)
T=LL(T);
else
T=LR(T);
}
T->ht=height(T);
return(T);
}
Example: Construct an AVL Tree by inserting numbers from 1 to 8.
Height of a node:
Height of a node can be calculated from the following C routine:
int height(node*T)
{
int lh,rh;
if(T==NULL)
return(0);
if(T->left==NULL)
lh=0;
else
lh=1+T->left->ht;
if(T->right==NULL)
rh=0;
else
rh=1+T->right->ht;
if(lh>rh)
return(lh);
return(rh);
}
Balance Factor:
For each AVL-tree node balance factor is need to be calculated.
The balance factor keeps track of the relative height difference between its left and right
subtrees,i.e.,
Balance Factor(BF) = height(left subtree) - height(right subtree).
Each node in a balanced binary tree has a balance of 1, - 1, or 0, depending on whether
the height of its left sub tree is greater than, less than, or equal to the height of its right sub
tree.
if(T->left==NULL)
lh=0;
else
lh=1+T->left->ht;
if(T->right==NULL)
rh=0;
else
rh=1+T->right->ht;
return(lh-rh);
}
Advantages:
1. Search is O(log n) since AVL trees are always balanced.
2. Insertion and deletions are also O(log n)
3. The height balancing adds no more than a constant factor to the speed of insertion.
Disadvantages:
1. Difficult to program & debug; more space for balance factor.
2. Asymptotically faster but rebalancing costs time.
3. Most large searches are done in database systems on disk and use other structures (e.g.
B-trees).
*********************
B - Tree
In search trees like binary search tree, AVL Tree, Red-Black tree, etc., every node contains
only one value (key) and a maximum of two children.
But there is a special type of search tree called B-Tree in which a node contains more
than one value (key) and more than two children.
B-Tree was developed in the year 1972 by Bayer and McCreight with the name Height
Balanced m-way Search Tree. Later it was named as B-Tree.
B-Tree is a self-balanced search tree in which every node contains multiple keys and has
more than two children.
Note:-
Here, the number of keys in a node and number of children for a node depends on the order
of B-Tree. Every B-Tree has an order.
For example, B-Tree of Order 4 contains a maximum of 3 key values in a node and
maximum of 4 children for a node.
Operations on a B-Tree
The following operations are performed on a B-Tree...
1. Search
2. Insertion
3. Deletion
Step 4 - If both are not matched, then check whether search element is smaller
or larger than that key value.
Step 5 - If search element is smaller, then continue the search process in left
subtree.
Step 6 - If search element is larger, then compare the search element with next
key value in the same node and repeate steps 3, 4, 5 and 6 until we find the
exact match or until the search element is compared with last key value in the
leaf node.
Step 7 - If the last key value in the leaf node is also not matched then display
"Element is not found" and terminate the function.
Delete Operation
The delete operation has more rules than insert and search operations.
The above diagram displays different cases of delete operation in a B-Tree. This B-Tree is of order
5, which means that the minimum number of child nodes any node can have is 3, and the
maximum number of child nodes any node can have is 5. Whereas the minimum and a maximum
number of keys any node can have are 2 and 4, respectively.
The target node has keys equal to minimum keys, so cannot delete it directly as it will
violate the conditions
The target node will borrow a key from immediate sibling, in this case, in-order
predecessor (left sibling) because it does not have any in-order successor (right sibling)
The maximum value of the inorder predecessor will be transferred to the parent, and the
parent will transfer the maximum value to the target node (see the diagram below)
The following example illustrates how to delete a key that needs a value from its in-order
successor.
The target node will borrow a key from immediate sibling, in this case, in-order successor
(right sibling) because it’s in-order predecessor (left sibling) has keys equal to minimum
keys.
The minimum value of the in-order successor will be transferred to the parent, and the
parent will transfer the maximum value to the target node.
In the example below, the target node does not have any sibling that can give its key to the target
node. Therefore, merging is required.
Merge the target node with any of its immediate siblings along with parent key
The key from the parent node is selected that siblings in between the two merging
nodes
Delete the target key from the merged node.
*********************
Red Block Tree
RBT Tree was invented in 1972 by Rudolf Bayer. It is a kind of BST and AVL tree
(Balancing Tree).
Red - Black Tree is another variant of Binary Search Tree in which every node is
colored either RED or BLACK.
We can define a Red Black Tree as follows...
Red Black Tree is a Binary Search Tree in which every node is colored either RED or
BLACK.
Property #4: In all the paths of the tree, there should be same number of BLACK colored
nodes.
Property #5: Every new node must be inserted with RED color.
Property #6: Every leaf (e.i. NULL node) must be colored BLACK.
Example
Following is a Red-Black Tree which is created by inserting numbers from 1 to 9.
Every Red Black Tree is a binary search tree but every Binary Search Tree need not be Red
Black tree
Insertion into RED BLACK Tree
In a Red-Black Tree, every new node must be inserted with the color RED. The insertion
operation in Red Black Tree is similar to insertion operation in Binary Search Tree.
But it is inserted with a color property. After every insertion operation, we need to check
all the properties of Red-Black Tree.
If all the properties are satisfied then we go to next operation otherwise we perform the
following operation to make it Red Black Tree.
1. Recolor
2. Rotation
3. Rotation followed by Recolor
The insertion operation in Red Black tree is performed using the following steps...
Step 1 - Check whether tree is Empty. If tree is Empty then insert the newNode as Root
node with color Black and exit from the operation.
Step 2 - If tree is not Empty then insert the newNode as leaf node with color Red.
Step 3 - If the parent of newNode is Black then exit from the operation.
Step 4 - If the parent of newNode is Red then check the color of parentnode's sibling of
newNode.
o 4(a) If it is colored Black or NULL then make suitable Rotation (hint –
o consider two movement node) and Recolor it.
o 4(b) If it is colored Red then perform Recolor(Black) & also check if parent’s
parent(i.e grand parent) of new node is not root node then recolor it & recheck
Step 5 - Repeat the same until tree becomes Red Black Tree.
Check :-
Root node is black
No two consecutive RED nodes
Count number of block node in all path, it should be same.
In splay tree, to splay any element we use the following rotation operations...
1. Zig Rotation
2. Zag Rotation
3. Zig - Zig Rotation
4. Zag - Zag Rotation
5. Zig - Zag Rotation
6. Zag - Zig Rotation
Zig Rotation
The Zig Rotation in splay tree is similar to the single right rotation in AVL Tree rotations. In zig
rotation, every node moves one position to the right from its current position. Consider the
following example...
Zag Rotation
The Zag Rotation in splay tree is similar to the single left rotation in AVL Tree rotations. In zag
rotation, every node moves one position to the left from its current position. Consider the
following example...
Zig-Zig Rotation
The Zig-Zig Rotation in splay tree is a double zig rotation. In zig-zig rotation, every node moves
two positions to the right from its current position. Consider the following example...
Zag-Zag Rotation
The Zag-Zag Rotation in splay tree is a double zag rotation. In zag-zag rotation, every node
moves two positions to the left from its current position. Consider the following example...
Zig-Zag Rotation
The Zig-Zag Rotation in splay tree is a sequence of zig rotation followed by zag rotation. In zig-
zag rotation, every node moves one position to the right followed by one position to the left from
its current position. Consider the following example...
Zag-Zig Rotation
The Zag-Zig Rotation in splay tree is a sequence of zag rotation followed by zig rotation. In zag-
zig rotation, every node moves one position to the left followed by one position to the right from
its current position. Consider the following example...
Every Splay tree must be a binary search tree but it is need not to be balanced tree.
Insertion Operation in Splay Tree
The insertion operation in Splay tree is performed using following steps...
Graph
Graph is a nonlinear data structure.
Graph => G={V,E}
o V=set of vertex ={v1,v2,….vn}
o E=set of edges={e1,e2….en}
Graph has no hierarchical relationship.
If a tree contains a closed loop or circuit, it is a
graph.
Vertex / Vertices
A node in a graph
Edge Graph
A line which connects two vertices.
Basic Terminology
1.Arc 2.Loop
The edge in a directed graph. Ex:- A->B A special case of a cycle in which a single
Arc arc begins and ends with the same vertex.
7.Degree of a vertex
8.Path
9. Adjacent node
Two nodes are adjacent if they connected via edge.
Types of Graph
1.Trivial Graph
A graph with only one vertex is called a Trivial Graph.
2.NULL Graph
A null graph does not contain any edges in it.
Here,
This graph consists of four vertices and four undirected edges.
4. Directed Graph-
A graph in which all the edges are directed is called as a directed graph.
Directed graphs are also called as digraphs.
Here,
Since all the edges are directed, therefore it is a directed graph
5. Connected Graph-
A graph in which we can visit from any one vertex to any other vertex is called as a
connected graph.
In connected graph, at least one path exists between every pair of vertices.
Here,
In this graph, we can visit from any one vertex to
any other vertex.
There exists at least one path between every pair of
vertices.
7. Regular Graph-
A graph in which degree of all the vertices is same is called as a regular graph.
If all the vertices in a graph are of degree ‘k’, then it is called as a “k-regular graph“.
In these graphs,
All the vertices have degree-2.
Therefore, they are 2-Regular
graphs.
8. Complete Graph-
A complete graph is a graph in which each pair of graph vertices is connected by an edge.
9. Simple Graph-
A graph having no self loops and no parallel edges in it is called as a simple graph.
Example-
Here,
10.Multi Graph-
A graph having no self loops but having parallel edge(s) in it is called as a multi graph.
Example-
Here,
Applications of Graphs
1. It used to represent communication network.
2. It used to represent electrical networks.
3. Graph coloring
4. Solving puzzles
5. Linguistics- The parsing tree of a language, Grammar of language.
6. Science-Molecular structure, Chemical structure, DNA structure.
---------------------------------------------------
Graph Representation
A graph can be represented using 3 data structures-
Adjacency matrix
Adjacency list
Adjacency multilists.
1.Adjacency Matrix
o Adjacency matrix is a sequential representation.
o It is used to represent which nodes are adjacent to each other. i.e. is there any edge
connecting nodes to a graph.
o In this representation, we have to construct a nXn matrix A. If there is any edge from a
vertex i to vertex j, then the corresponding element of A, ai,j = 1, otherwise ai,j= 0.(Or) If two
vertices are adjacent (there is an edge between them) the matrix insect has a value of 1 ,
otherwise , it is zero.
o Types of Adjacency Matrix:-
(1) Undirected Graph Representation
In the above example, 1 represents an edge from row vertex to column vertex, and 0
represents no edge from row vertex to column vertex.
2.Adjacency list
In Adjacency List, we use an array of a list to represent the graph.
The list size is equal to the number of vertex(n).
Let's assume the list of size n as Adjlist[n]
Adjlist[0] will have all the nodes which are connected to vertex 0.
Adjlist[1] will have all the nodes which are connected to vertex 1 and so on.
3.Adjacency Multilist
Modified version of a adjacency lists.
Edge-based rather than a vertex-based representation of graphs.
OR
M -> A single bit field to indicate whether the edge has beeb examined or not.
Vi -> AVertex in the graph that is connected to vertex Vj by an edge.
Vj -> A Vertex in the graph that is connected to vertex Vi by an edge.
Link i for Vi or (Link1) -> A link that points to another node that has an edge incident on Vj.
Link j for Vi or (Link2) -> A link that points to another node that has an edge incident on Vi.
----------------------------------
Graph Traversal
In simple words, traversal means the process of visiting every node in the graph. There are 2
standard methods of graph traversal Breadth-First Search and Depth First Search.
BFS Routine
---------------------------------------
2.Depth First Search
Depth First Search (DFS) is a graph traversal algorithm, where we start from a
selected(source) node and go into the depth of this node by recursively calling
the DFS function until no children are encountered.
When the dead-end is reached, this algorithm backtracks and starts visiting the other
children of the current node.
DFS Algorithm
1.Put the starting vertex into the stack , mark it as visited.
Display it
2.If (Stack[Top] has adjacent unvisited vertex) Then
{
Visit the adjacent unvisited vertex and mark it as visited.
Push it into the stack.
Display it.
}
Else
{
Pop the top element from the stack.(Back tracking)
}
Repeat Step-2 Until stack is empty.
DFS Routine
-------------------------
Disjoint-Set
The Disjoint-set data structure is useful when we have a collection of items that are
divided into one or more pairwise disjoint sets (hence the name of the data structure), meaning
that no item is in more than one set. An example of this are the connected components of
an undirected graph, just like the one represented in the image below:
If we are dealing with items, then is an array of size , and the th element of the
array represents the th item. More precisely, the th element of the array is the parent of the th
item. These relationships create one, or more, virtual trees. The following image to better
understand it.
There you can see that is under in the tree, because . Also note that and have
no parents, because parent[2]=-1 and parent[3]=-1 .
Each tree is a disjoint set. If two elements are in the same tree, then they are in the same disjoint
set. The root node (or the topmost node) of each tree is called the representative of the set. There is
always a single unique representative of each set.
If is not the representative of his set, then it can be found by traveling up the tree until we find
the representative.
Union Operation
the Union operation is simple to implement. It takes, as input, two elements, finds the
representatives of their sets using the Find operation, and finally puts either one of the trees
(representing the set) under the root node of the other tree, effectively merging the trees and the
sets. If we would call Union on the two trees in the image example above, the result would be the
following:
2. Union Operation:
//merging or join two disjoint sets
int union(int i,int j)
{
parent[j]=i;
}
---------------------------------
Minimum spanning tree can be defined as the spanning tree in which the sum
of the weights of the edge is minimum. The weight of the spanning tree is the
sum of the weights given to the edges of the spanning tree.
The minimum spanning tree is a spanning tree whose sum of the edges is
minimum.
Note:-
1.Weight of the edges should be minimum
2.Don’t form a cycle
Prim’s Algorithm-
Prim's algorithm is a minimum spanning tree algorithm that takes a graph as input and finds the
subset of the edges of that graph which
form a tree that includes every vertex
has the minimum sum of weights among all the trees that can be formed from the graph
Steps:
1. Select a starting vertex
2. Repeat Steps 3 and 4 until there are fringe vertices
3. Select an edge 'e' connecting the tree vertex and fringe vertex that has minimum weight
4. Add the selected edge and the vertex to the minimum spanning tree T
5. EXIT
Example
Kruskal’s Algorithm-
Kruskal's algorithm is a minimum spanning tree algorithm that takes a graph as input and finds
the subset of the edges of that graph which
form a tree that includes every vertex
has the minimum sum of weights among all the trees that can be formed from the graph
Steps
1. Sort all the edges from low weight to high weight.
2. Take the edge with the lowest weight and use it to connect the vertices of graph.
If adding an edge creates a cycle, then reject that edge and go for the next
least weight edge.
3. Keep adding edges until all the vertices are connected and a Minimum Spanning
Tree (MST) is obtained.
***************
Question Bank
Unit – 1
Part –A
1. Define Data Structures.
A data structure is a method for organizing and storing data which would allow
efficient data retrieval and usage.
A data structure is a way of organizing data that considers not only the items
stored, but also their relationships to each other.
15. Difference between Abstract Data Type, Data Type and Data Structure.
An Abstract data type is the specification of the data type which specifies
the logical and mathematical model of the data type.
A data type is the implementation of an abstract data type. Data type has
its root in the abstract data type and a data structure comprises a set of
computer variables of same or different data types
Data structure refers to the collection of computer variables that are
connected in some specific manner.
16. What are the two main classification of sorting based on the source of data?
According to the source of data sorting is classified into, a.External sorting b.Internal
sorting
17. What are the various factors to be considered in deciding a sorting algorithm?
Factors to be considered in deciding a sorting algorithm are,
a.Programming time
b.Executing time for program
c.Memory or auxiliary space needed for the programs environment
20. Is the heap sort always better than the quick sort?
No, the heap sort does not perform better than the quick sort. Only when array is
nearly sorted to begin with the heap sort algorithm gains an advantage. In such a
case, the quick deteriorates to its worst performance of O (n2).
24. How does the bubble sort differ from the selection sort?
In selection sort, we find the smallest record and then perform an interchange.
Whereas in bubble sort, two records are interchanged immediately upon
discovering that they are out of order.
Unit - 1
Part – B
1) What is the best time complexity of bubble sort? Example with its implementation?
2) Explain in detail about sorting and different types of sorting techniques
3) 3 Write a program to explain insertion sort . Which type of technique does it
belong.(or)Write a C-program for sorting integers in ascending order using insertion sort.
4) Solve the insertion sort results for each insertion for the following initial array of elements.
25, 6, 15,12 ,8 ,34,9 ,18 ,2
5) Demonstrate the selection sort results for each pass for the following initial array of
elements. 21, 6, 3, 57 ,13, 9, 14 ,18, 2
6) Explain the algorithm for QUICK sort (partition exchange sort) and give a suitable
example
7) Explain the algorithm for Merge sort and give a suitable example.
8) Write a program to implement Quick sort
9) Write a program to implement Merge sort.
10) Explain a sorting technique which follows divide and conquer mechanism with an
example. (quick & merge sorts)
11) Write and explain linear search procedure or algorithm with a suitable example.
12) Formulate recursive algorithm for binary search with its timing analysis.
13) Write a C program that searches a value in a stored array using linear search.
14) Write a program for recursive binary search to find the given element within array. For
What data binary search is not applicable?
15) Write a C program that searches a value in a stored array using non recursive binary
search
16) Define a data structure. What are the different types of data structures? Explain each of
them with suitable example.
Unit – 2
Part –A
1. Define Stack.
Stack is an ordered collection of elements in which insertions and deletions are
restrictedto one end. The end from which elements are added and/or removed is referred
to as top of the stack. Stacks are also referred as piles, push-down lists and last-in-first-
out (LIFO) lists.
A * (B + C) / D
A B C + * D/
/*A+BCD
Move the operators one by one to their right, such that each operator replaces
their corresponding right parenthesis
The part of the expression, which has been converted into postfix is to be
treated assingle operand
15. What is a Queue, how it is different from stack and how is it implemented?
Queue is a linear structure which follows the order is First in First out (FIFO) to
access elements.
24. What are enqueue and dequeue operations? (Nov/Dec 2014)(April/May 2016)(R)
Enqueue - adding an element to the queue at the rear end
Dequeue – removing or deleting an element from the queue at
thefront end
Unit - 2
Part – B
Unit – 3
Part –A
1. Define List ADT
A list is a sequence of zero or more elements of a given type. The list is represented
as sequence of elements separated by comma. A1, A2, A3…..AN Where N>0 and
A is of type element.
Doubly linked list is a collection of nodes where nodes are connected by forwarded and backward
link. Each node has three fields:
Address of previous node
Data
Address of next node.
14) What are the merits and demerits of array implementation of lists?
Merits:
1. Fast, random access of elements
2. Memory efficient – very less amount of memory is required Demerits.
3. Insertion and deletion operations are very slow since the elements should be moved.
4. Redundant memory space – difficult to estimate the size of array.
21) Difference between Singly Linked List, Doubly Linked List and Circular Linked List
Unit - 3
Part – B
Unit – 4
Part –A
1. Define tree.
Trees are non-liner data structure, which is used to store data items in a
shorted sequence. It represents any hierarchical relationship between any data Item.
It is a collection of nodes, which has a distinguish node called the root and zero or
more nonempty sub trees T1, T2,….Tk. each of which are connected by a directed
edge fromthe root.
The level of a node is defined by 1 + the number of connections between the node and the
root. Note: level is depth plus 1.
8. Define sibling?
Nodes with the same parent are called siblings.
AVL tree also called as height balanced tree .It is a height balanced tree in which every
node will have a balancing factor of –1, 0, and 1.Balancing factor of a node is given by
the difference between the height of the left sub tree and the height of the right sub tree.
11. What are the various operation performed in the binary search tree?
insertion
deletion
find
find min
find max
19. What are the tasks performed while traversing a binary tree?
Visiting a node
Traverse the left sub-tree
Traverse the right sub-tree
30. Why it is said that searching a node in a binary search tree is efficient than that of a
simple binary tree?
In binary search tree, the nodes are arranged in such a way that the left node is having
less data value than root node value and the right nodes are having larger value than that
of root. Because of this while searching any node the value of the target node will be
compared withthe parent node and accordingly either left sub branch or right sub branch
will be searched. So, one has to compare only particular branches. Thus searching
becomes efficient.
disk accesses for most of the operations are reduced significantly compared to balanced
Binary Search Trees like AVL Tree, Red Black Tree.
minimum 1key. All nodes (including root) may contain at most 2t – 1 keys.
Number of children of a node is equal to the number of keys in it plus 1.
All keys of a node are sorted in increasing order. The child between two keys k1
and k2 contains all keys in range from k1 and k2.
B-Tree grows and shrinks from root which is unlike Binary Search Tree.
BinarySearch Trees grow downward and also shrink from downward.
Like other balanced Binary Search Trees, time complexity to search, insert
anddelete is O(Logn).
36. Show the result of in order tree traversal from the figure given below
Unit - 4
Part – B
1) Write a c-program to implement binary search tree with an example
2) List the types of Binary Search Tree. Explain Insertion and Deletion Operation on Binary
Search Tree with Example.
3) Explain Tree Traversal with Example.
4) Create a Binary Search Tree for the following data and do in-order, Preorder and Post-
order traversal of the tree.50, 60, 25, 40, 30, 70, 35, 10, 55, 65, 5
5) What is the meaning of height balanced tree? How rebalancing is done in height balanced
tree
6) What is priority queue? Explain different types of priority queue with an example.
7) Define an AVL tree. Obtain an AVL tree by inserting one integer at a time in the following
sequence.150, 155, 160, 115, 110, 140, 120, 145, 130, 147, 170, 180.Show all the steps.
8) What is the difference between a binary tree and binary search tree, explain with an
example.
9) What is red black tree? Explain with an example?
10) What is splaying? Explain different types of splay trees?
11) What is B-tree? Insert the following elements into B-Tree 10,12,5,34,89, 4, 78,90.
[Order (m)=3]
12) Explain the different types of rotations in AVL trees with an example?
13) Explain Max Heap and Min Heap.
Unit – 5
Part –A
1. Define adjacent nodes.
Any two nodes which are connected by an edge in a graph are called adjacent nodes. For
example, if an edge x ε E is associated with a pair of nodes (u,v) where u, v ε V, then we
say that the edge x connects the nodes u and v.
4. What is a loop?
An edge of a graph which connects to itself is called a loop or sling.
From the graph earlier, the out-degree sequence (blue degrees) is (0,1,1,1,2,3), while the
in- degree sequence (red degrees) is (0,1,1,2,2,2).
15. What are the two traversal strategies used in traversing a graph?
a. Breadth first search
b. Depth first search
Aircraft scheduling
Bi-processor tasks
Pre-colouring extension
Time table scheduling
Fingerprint reconstruction
26. List the two important key points of depth first search.
If path exists from one node to another node, walk across the edge – exploring the
edge.
If path does not exist from one specific node to any other node, return to the
previous node where we have been before – backtracking.
Unit - 5
Part – B
PART – B
Answer any FIVE questions
All questions carry equal marks
5 x 10
1. a) Write a C program to search key element in the list using binary search.
b) Apply selection sort to sort given elements in ascending order 7,4,2,1,9,3,8
2. a) What is stack overflow and underflow? Give examples.
b) What is the limitation of linear queue? How it is overcome using circular queue?
3. a) Design an algorithm to evaluate postfix expression using stack
b) Write C function to display circular queue using array.
4. a) Write the node structure of singly linked list (SLL). Develop a C function to count the number
of nodes in a SLL.
b) Write a C function to insert new element after the given position on doubly linked list.
5. a) Write a C function to display doubly linked list contents in reverse order.
b) Explain how circular linked list is different from singly linked list.
6. a) Define with examples the terms siblings, level and depth with respect to tree data structure.
b) What are threaded binary trees? List any 2 applications of it.
7. a) Define Binary Search Tree (BST). Construct a BST for the list 5,2,9,1,7,3.
b) What is the difference between binary tree and strictly binary tree? Give examples.
8. a) What is spanning tree? Write kuskal’s algorithm to generate spanning tree.
b) Differentiate breadth first search and depth first search with examples.
🙚*🙚
Code No.: 20ES117
II B.TECH. II SEM. (R20) REGULAR EXAMINATIONS, MAY – 2022
DATA STRUCTURES AND ALGORITHMS
(ECE, ECE[AIML, IOT])
PART – B
Answer any FIVE questions
All questions carry equal marks
5 x 10
1. Explain how the stack is used to convert the following infix expression into postfix form
a/b-c+d*e-a*c and evaluate that postfix expression for given data a=6, b=3, c=1, d=2, e=4.
2. a) Show the result of inserting 3,1,4,6,9,2,5,7 into an initially empty binary search tree.
b) Define a stack? Write all the stack operations.
3. a) Construct a binary tree having the following traversal sequences:
Preorder traversal: A B C D E F G H I
Inorder traversal: B C A E D G H F I
b) Write a short note on Graph representation with suitable example.
4. Write the pseudo code to find a minimum spanning tree using Prim’s algorithm.
5. Draw the steps required to perform a single right rotation and double LR rotation in an AVL Tree.
6. Write an algorithm for Quick sort and differentiate Insertion sort, and Bubble sort.
7. Construct max heap for the following elements:
40, 80, 30, 20, 10, 40, 30, 60, 100, 70.
8. Write an algorithm to perform all delete operations on double linked list.
🙚*🙚