SlideShare a Scribd company logo
MCA_Data Structure_Notes_of_UNIT_I & II.pdf
Introduction to data structure: Data, Entity, Information,
Difference between Data and Information, Data type , Build in data
type, Abstract data type, Definition of data structures, Types of
Data Structures: Linear and Non-Linear Data Structure, Introduction
to Algorithms: Definition of Algorithms, Difference between
algorithm and programs, properties of algorithm, Algorithm Design
Techniques, Performance Analysis of Algorithms, Complexity of
various code structures, Order of Growth, Asymptotic Notations.
Data, Entity, and Information
 Data: Data refers to raw, unprocessed facts and figures without context.
These can be numbers, characters, symbols, or even just bits of information
that by themselves may not make sense. Data can be quantitative (numbers)
or qualitative (descriptions).
 Entity: An entity is an object or a thing that exists and can be distinctly
identified. In databases, an entity is anything about which data can be
collected, such as a person, place, event, or concept.
 Information: Information is processed, organized, or structured data that is
meaningful and useful for decision-making. When data is interpreted and
presented in context, it becomes information.
Difference between Data and Information
 Data: Raw, unprocessed facts. For example, 123, John, and apple.
 Information: Processed data that is meaningful and used for decision-
making. For example, "John bought 3 apples."
Data Type
 Data Type: A data type is a classification that specifies which type of value a
variable can hold and what operations can be performed on it. Common data
types include integers, floating-point numbers, characters, and booleans.
Built-in Data Types
 Built-in Data Types: The basic data types provided by a programming
language. Examples in many languages include:
 Integer (int): Represents whole numbers.
 Floating-point (float): Represents real numbers with fractional parts.
 Character (char): Represents single characters.
 Boolean (bool): Represents truth values (true or false).
Abstract Data Type (ADT)
 Abstract Data Type (ADT): A model for data structures that specifies the
type of data stored, the operations supported on them, and the types of
parameters of the operations. Examples include Stack, Queue, List, and Tree.
Definition of Data Structures
 Data Structures: A data structure is a way of organizing, managing, and
storing data in a computer so that it can be accessed and modified efficiently.
It defines the relationship between the data, the operations that can be
performed on the data, and how the data can be manipulated. Examples
include arrays, linked lists, stacks, queues, trees, and graphs.
Types of Data Structures
 Linear Data Structures: Elements are arranged in a sequential manner.
Examples include:
 Array: A collection of elements identified by index or key.
 Linked List: A sequence of elements where each element points to
the next one.
 Stack: A collection of elements that follows Last in First out (LIFO)
principle.
 Queue: A collection of elements that follows First in First out (FIFO)
principle.
 Non-Linear Data Structures: Elements are not arranged in a sequential
manner. Examples include:
 Tree: A hierarchical structure with a root element and a collection of
child elements.
 Graph: A set of nodes (vertices) connected by edges.
Introduction to Algorithms
 Definition of Algorithms: An algorithm is a step-by-step procedure or
formula for solving a problem. It is a sequence of instructions that are followed
to perform a task or solve a problem.
Difference between Algorithm and Program
 Algorithm: A conceptual solution to a problem, expressed in terms of steps.
 Program: A concrete implementation of an algorithm written in a specific
programming language.
Properties of Algorithm
 Finiteness: The algorithm must terminate after a finite number of steps.
 Definiteness: Each step must be precisely defined.
 Input: An algorithm has zero or more inputs.
 Output: An algorithm produces one or more outputs.
 Effectiveness: Each step must be basic enough to be carried out, in
principle, by a person using only paper and pencil.
Algorithm Design Techniques
 Divide and Conquer: Breaking the problem into smaller sub-problems,
solving each sub-problem individually, and combining their solutions.
 Dynamic Programming: Solving complex problems by breaking them into
simpler sub-problems and storing the results of these sub-problems to avoid
redundant work.
 Greedy Algorithm: Making the locally optimal choice at each stage with the
hope of finding a global optimum.
 Backtracking: Trying out different solutions and abandoning them if they do
not work.
 Branch and Bound: Optimizing a solution by dividing it into sub-problems
and pruning the ones that do not meet the criteria.
Performance Analysis of Algorithms
 Complexity of Various Code Structures: Evaluating the efficiency of
algorithms in terms of time and space.
 Time Complexity: How the execution time of an algorithm changes
with the input size.
 Space Complexity: How the memory usage of an algorithm changes
with the input size.
Order of Growth:
 Describes the behavior of the complexity function as the input size grows.
 Common orders of growth include constant (O(1)), logarithmic (O(log n)),
linear (O(n)), linearithmic (O(n log n)), quadratic (O(n²)), cubic (O(n³)), and
exponential (O(2^n)).
Asymptotic Notations:
 Big O (O): Upper bound of the complexity; worst-case scenario.
 Omega (Ω): Lower bound of the complexity; best-case scenario.
 Theta (Θ): Tight bound of the complexity; average-case scenario when both
the upper and lower bounds are the same.
Arrays: Definition, Single and Multidimensional Arrays,
Representation of Arrays: Row Major Order, and Column Major
Order, Derivation of Index Formulae for 1-D,2-D Array Application
of arrays, Sparse Matrices and their representations.
Arrays
Definition: An array is a collection of elements, all of the same type, stored in
contiguous memory locations. Each element is accessed by an index.
Types of Arrays
 Single-dimensional Arrays (1-D Arrays): A single-dimensional array is a
linear sequence of elements, all of the same type. It is often referred to as a
list.
 Two-dimensional Arrays (2-D Arrays): These are like a table or a matrix
with rows and columns.
 Multidimensional Arrays: Multidimensional arrays are arrays of arrays. They
can have two or more dimensions.
 Higher-dimensional Arrays: These can be 3D, 4D, etc., and are used for
more complex data structures.
Demo of Single-dimensional Array
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int i;
void create(int[],int);
void display(int ar[],int len);
int search(int ar[],int len,int k);
void insert(int ar[],int *len);
void del(int ar[],int *len);
void main()
{
int ar[10],size,ch,pos,k;
do
{
clrscr();
printf("nt********MENU**********n");
printf("ntt1. Create");
printf("ntt2. Display");
printf("ntt3. Search");
printf("ntt4. Insert");
printf("ntt5. Delete");
printf("ntt6. Exit");
lb:
printf("nntEnter your choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("nHow many do you want to insert: ");
scanf("%d",&size);
create(ar,size);
break;
case 2:
display(ar,size);
break;
case 3:
printf("nEnter the value to be search: ");
scanf("%d",&k);
pos=search(ar,size,k);
if(pos==-1)
printf("nElement not found");
else
printf("nElement found at %d position",
pos+1);
break;
case 4:
insert(ar,&size);
break;
case 5:
del(ar,&size);
break;
case 6:
exit(0);
default:
printf("naInvalid choice!!");
goto lb;
}
getch();
}while(1);
}
void create(int ar[],int len)
{
printf("nEnter %d elements of array: ",len);
for(i=0;i<len;i++)
scanf("%d",&ar[i]);
}
void display(int ar[],int len)
{
if(len<0 || len>10)
{
printf("ntaFirst create the array!");
getch();
return;
}
printf("nArray's elements are as follows: ");
for(i=0;i<len;i++)
printf(" %d",ar[i]);
}
int search(int ar[],int len,int k)
{
for(i=0;i<len;i++)
if(ar[i]==k)
return(i);
return(-1);
}
void insert(int ar[],int *len)
{
int k,pos;
printf("nEnter the value after which insertion is required: ");
scanf("%d",&k);
pos=search(ar,*len,k);
if(pos==-1)
{
printf("nElement not found");
return;
}
for(i=*len;i>pos;i--)
ar[i]=ar[i-1];
printf("nEnter the value to be insert: ");
scanf("%d",&ar[pos+1]);
*len+=1;
}
void del(int ar[],int *len)
{
int k,pos;
printf("nEnter the value to be delete: ");
scanf("%d",&k);
pos=search(ar,*len,k);
if(pos==-1)
{
printf("nElement not found");
return;
}
for(i=pos;i<*len;i++)
ar[i]=ar[i+1];
*len-=1;
}
Demo of Two-dimensional Array
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int i,j,k;
void get_mat(int x[][10],int r,int c);
void dis_mat(int x[][10],int r,int c);
void main()
{
int a[10][10],b[10][10],c[10][10],r1,c1,r2,c2;
lb:
clrscr();
printf("nEnter the dimention of first mattrix (RxC): ");
scanf("%d%d",&r1,&c1);
printf("nEnter the dimention of second mattrix (RxC): ");
scanf("%d%d",&r2,&c2);
if(c1!=r2)
{
printf("nMattrix are not compatible!");
printf("nPress any key to try again....");
goto lb;
}
printf("nEnter the elements of first mattrix: ");
get_mat(a,r1,c1);
printf("nThe first mattrix is as follows:n");
dis_mat(a,r1,c1);
printf("nEnter the elements of second mattrix: ");
get_mat(b,r2,c2);
printf("nThe second mattrix is as follows:n");
dis_mat(b,r2,c2);
for(i=0;i<r1;i++)
for(j=0;j<c2;j++)
{
c[i][j]=0;
for(k=0;k<c1;k++)
c[i][j]+=a[i][k]*b[k][j];
}
printf("nMultipication of Mattrix are as follows:n");
dis_mat(c,r1,c2);
getch();
}
void get_mat(int x[][10],int r,int c)
{
for(i=0;i<r;i++)
for(j=0;j<c;j++)
scanf("%d",&x[i][j]);
}
void dis_mat(int x[][10],int r,int c)
{
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
printf(" %d ",x[i][j]);
printf("n");
}
}
Representation of Arrays
 Row Major Order: In row major order, the elements of a multi-dimensional
array are stored row by row. For example, in a 2-D array, the first row is
stored in contiguous memory locations, followed by the second row, and so
on.
 Column Major Order: In column major order, the elements of a multi-
dimensional array are stored column by column. For example, in a 2-D array,
the first column is stored in contiguous memory locations, followed by the
second column, and so on.
Derivation of Index Formulae
 1-D Array: The index formula for accessing the ith element of a 1-D array A
with base address B is:
Address(𝐴[𝑖])=𝐵+𝑖× size_of_each_element
 2-D Array: For a 2-D array A with m rows and n columns, the element at
position (𝑖,𝑗) can be accessed using the following formulas:
 Row Major Order:
Address(𝐴[𝑖][𝑗])=𝐵+((𝑖×𝑛)+𝑗)×w
 Column Major Order:
Address(𝐴[𝑖][𝑗])=𝐵+((𝑗×𝑚)+𝑖)×w
Where:
o B is the base address of the array.
o i and j are the row and column indices, respectively.
o n is the total number of columns in the array.
o m is the total number of rows in the array.
o w is the size of each element
Applications of Arrays
 Storing and accessing sequential data: Arrays are used to store a
sequence of elements which can be accessed by an index.
 Matrix operations: Arrays are used in mathematical computations, especially
matrices.
 Buffers in Input/Output operations: Arrays are used to store data
temporarily during I/O operations.
 Implementing data structures: Arrays are fundamental in implementing
other data structures like stacks, queues, and heaps.
 Image processing: Pixels of an image are stored in 2-D arrays.
Sparse Matrices and Their Representations
 Sparse Matrix: A sparse matrix is a matrix in which most of the elements are
zero. Efficient storage techniques are used to save space and reduce
computational complexity.
Linked lists: Array Implementation and Pointer Implementation of
Singly Linked Lists, Doubly Linked List, Circularly Linked List,
Operations on a Linked List. Insertion, Deletion, Traversal,
Polynomial Representation and Addition Subtraction &
Multiplications of Single variable.
Linked List Overview
A linked list is a linear data structure where elements, called nodes, are not stored in
contiguous memory locations. Each node contains two parts:
 Data: Stores the value.
 Pointer (or Reference): Points to the next node in the sequence.
Types of Linked Lists
 Singly Linked Lists
A singly linked list is a data structure consisting of nodes where each node
contains data and a reference (or pointer) to the next node in the sequence.
Node Structure:
struct Node
{ int data;
Node* next;
};
 Doubly Linked Lists
A doubly linked list is a data structure consisting of nodes where each node
contains data, a reference to the next node, and a reference to the previous
node.
Node Structure:
struct Node
{
int data;
Node* next; * prev;
};
 Circularly Linked Lists
A circularly linked list is a data structure where the last node points to the first
node, forming a circle. It can be either singly or doubly linked.
Singly Circularly Linked List Node Structure:
struct Node
{ int data;
Node* next;
};
Basic Operations
 Insertion:
 At the beginning:
o Update the new node's next pointer to the current head.
o Update the head to the new node.
 At the end:
o Traverse to the last node.
o Update the last node's next pointer to the new node.
o Update the new node's next pointer to null (or the head in
circular lists).
 At a given position:
o Traverse to the node before the desired position.
o Update the new node's next pointer to the current node's next
pointer.
o Update the current node's next pointer to the new node.
 Deletion:
 From the beginning:
o Update the head to the next node.
o Free the old head node.
 From the end:
o Traverse to the second last node.
o Update its next pointer to null.
o Free the last node.
 From a given position:
o Traverse to the node before the desired position.
o Update its next pointer to the next node's next pointer.
o Free the node at the given position.
 Traversal:
Start from the head and follow the next pointers until reaching the end (null for
singly linked lists, the head for circular linked lists).
Demo of Singly Linked Lists
#include <stdio.h>
#include <stdlib.h>
struct node
{
int info;
struct node* next;
}*start=NULL;
typedef struct node NODE;
void main()
{
int ch,a;
char c;
NODE *n_node,*temp,*before,*after;
lb:
clrscr();
printf("ntt******MENU******n");
printf("nttt1. Create");
printf("nttt2. Display");
printf("nttt3. Insertion start");
printf("nttt4. Insertion mid");
printf("nttt5. Deletion");
printf("nttt6. Exit");
printf("nntEnter your choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1:
do
{
n_node=(NODE*)malloc(sizeof(NODE));
printf("ntEnter the elemenet: ");
scanf("%d",&n_node->info);
if(start==NULL)
{
n_node->next=start;
start=n_node;
}
else
{
temp=start;
while(temp->next)
temp=temp->next;
n_node->next=temp->next;
temp->next=n_node;
}
printf("ntWant to enter more element (y/n): ");
fflush(stdin);
scanf("%c",&c);
}while(c=='Y'||c=='y');
break;
case 2:
temp=start;
printf("ntList ementents are: ");
while(temp)
{
printf("%d->",temp->info);
temp=temp->next;
}
printf("NULL");
break;
case 3:
n_node=(NODE*)malloc(sizeof(NODE));
printf("ntEnter the elemenet to be insert: ");
scanf("%d",&n_node->info);
n_node->next=start;
start=n_node;
break;
case 4:
n_node=(NODE*)malloc(sizeof(NODE));
printf("ntEnter the elemenet to be insert: ");
scanf("%d",&n_node->info);
printf("ntEnter the elemenet after which insertion is
required: ");
scanf("%d",&a);
temp=start;
while(temp)
{
if(temp->info==a)
break;
temp=temp->next;
}
if(temp==NULL)
{
printf("ntElement not found.");
break;
}
n_node->next=temp->next;
temp->next=n_node;
break;
case 5:
printf("ntEnter the element to be delete: ");
scanf("%d",&a);
if(start->info==a)
{
temp=start->next;
free(start);
start=temp;
break;
}
before=start;
while(before)
{
if(before->next->info==a)
break;
before=before->next;
}
if(before==NULL)
{
printf("ntElement not found.");
break;
}
temp=before->next;
after=temp->next;
before->next=after;
free(temp);
break;
case 6:
exit(0);
default:
printf("ntaInvalid Choice!!");
}
getch();
goto lb;
}
Demo of Doubly Linked Lists
#include <stdio.h>
#include <stdlib.h>
struct node
{
int info;
struct node* next,*prev;
}*start=NULL;
typedef struct node NODE;
void main()
{
int ch,a;
char c;
NODE *n_node,*temp,*before,*after;
lb:
clrscr();
printf("ntt******MENU******n");
printf("nttt1. Create");
printf("nttt2. Display");
printf("nttt3. Insertion start");
printf("nttt4. Insertion mid");
printf("nttt5. Deletion");
printf("nttt6. Exit");
printf("nntEnter your choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1:
do
{
n_node=(NODE*)malloc(sizeof(NODE));
printf("ntEnter the elemenet: ");
scanf("%d",&n_node->info);
if(start==NULL)
{
n_node->next=start;
start=n_node;
}
else
{
temp=start;
while(temp->next)
temp=temp->next;
n_node->next=temp->next;
n_node->prev=temp;
temp->next=n_node;
}
printf("ntWant to enter more element (y/n): ");
fflush(stdin);
scanf("%c",&c);
}while(c=='Y'||c=='y');
break;
case 2:
temp=start;
printf("ntList ementents are: ");
while(temp)
{
printf("%d->",temp->info);
temp=temp->next;
}
printf("NULL");
break;
case 3:
n_node=(NODE*)malloc(sizeof(NODE));
printf("ntEnter the elemenet to be insert: ");
scanf("%d",&n_node->info);
n_node->next=start;
start->prev=n_node;
start=n_node;
break;
case 4:
n_node=(NODE*)malloc(sizeof(NODE));
printf("ntEnter the elemenet to be insert: ");
scanf("%d",&n_node->info);
printf("ntEnter the elemenet after which insertion is
required: ");
scanf("%d",&a);
before=start;
while(before)
{
if(before->info==a)
break;
before=before->next;
}
if(before==NULL)
{
printf("ntElement not found.");
break;
}
after=before->next;
n_node->next=after;
after->prev=n_node;
before->next=n_node;
n_node->prev=before;
break;
case 5:
printf("ntEnter the element to be delete: ");
scanf("%d",&a);
if(start->info==a)
{
temp=start->next;
free(start);
start=temp;
break;
}
before=start;
while(before)
{
if(before->next->info==a)
break;
before=before->next;
}
if(before==NULL)
{
printf("ntElement not found.");
break;
}
temp=before->next;
after=temp->next;
before->next=after;
after->prev=before;
free(temp);
break;
case 6:
exit(0);
default:
printf("ntaInvalid Choice!!");
}
getch();
goto lb;
}
Advantages of Linked Lists
 Dynamic Size: Can grow or shrink in size as needed.
 Efficient Insertions/Deletions: Insertion and deletion operations are
efficient, particularly when dealing with large datasets.
Disadvantages of Linked Lists
 Memory Usage: Requires extra memory for storing pointers.
 No Random Access: Accessing elements by index requires traversing from
the head.
Use Cases
 Dynamic Data: Useful when the size of the data is not known beforehand and
needs frequent insertions/deletions.
 Real-Time Systems: Where low latency for insertion/deletion is crucial.
 Implementing Other Data Structures: Such as stacks, queues, and
associative arrays.
Variants and Applications
 Stack: Implemented using singly linked lists with insertion and deletion at the
head.
 Queue: Implemented using singly linked lists with insertion at the end and
deletion at the head.
 Doubly Linked List Applications: Useful in scenarios where bidirectional
traversal is required, such as in navigation systems.
 Circular Linked List Applications: Useful in applications that need a cyclic
iteration, such as round-robin scheduling.
Polynomial Representation Using Linked Lists
Polynomials can be efficiently represented using linked lists where each node stores
the coefficient and exponent of a term.
Node Structure:
struct Node
{
int coeff,exp;
Node* next;
};
 Polynomial Addition:
 Traverse both polynomials, adding terms with the same exponents and
creating new nodes for terms with unique exponents.
 Polynomial Multiplication:
 Multiply each term of the first polynomial with each term of the second
polynomial.
 Combine like terms and create a new polynomial.
MCA_Data Structure_Notes_of_UNIT_I & II.pdf
Stacks: Abstract Data Type, Primitive Stack operations: Push &
Pop, Array and Linked Implementation of Stack in C, Application of
stack: Prefix and Postfix Expressions, Evaluation of postfix
expression, Iteration and Recursion- Principles of recursion, Tail
recursion, Removal of recursion Problem solving using iteration
and recursion with examples such as binary search, Fibonacci
numbers, and Hanoi towers.
Stacks: Abstract Data Type
Stack is a linear data structure that follows the Last In, First Out (LIFO) principle. In
this structure, the most recently added element is the first one to be removed. The
basic operations for a stack include:
 Push: Add an element to the top of the stack.
 Pop: Remove and return the element from the top of the stack.
 isEmpty: Check if the stack is empty.
 isFull: Check if the stack is full (in case of a fixed-size stack).
Array and Linked List Implementation of Stack
 Array Implementation:
 Utilizes a fixed-size array.
 A variable (top) keeps track of the index of the top element.
 Advantages: Simple and efficient for small datasets.
 Disadvantages: Fixed size, requires resizing if the stack grows beyond
its initial capacity.
Demo of Stack using Array Implementation
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int s[5],ch,i,tos=-1;
do
{
clrscr();
printf("nt********MENU**********n");
printf("ntt1. PUSH");
printf("ntt2. POP");
printf("ntt3. Display");
printf("ntt4. Exit");
lb:
printf("nntEnter your choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1:
if(tos==4)
{
printf("ntStack is overflow!");
break;
}
printf("ntEnter element to PUSH: ");
scanf("%d",&s[++tos]);
break;
case 2:
if(tos==-1)
{
printf("ntStack is underflow!");
break;
}
printf("ntElement POPPed is: %d",s[tos--]);
break;
case 3:
if(tos==-1)
{
printf("ntStack is underflow!");
break;
}
printf("ntStack Elements are :");
for(i=tos;i>=0;i--)
printf("ntttt%d",s[i]);
break;
case 4:
exit(0);
default:
printf("natInvalid choice!!");
goto lb;
}
getch();
}while(1);
}
 Linked List Implementation:
 Each element is a node containing data and a reference to the next
node.
 A pointer (top) points to the most recently added node.
 Advantages: Dynamic size, no need for resizing.
 Disadvantages: More complex memory management due to dynamic
allocation.
Demo of Stack using Linked List Implementation
#include <stdio.h>
#include <stdlib.h>
struct node
{
int info;
struct node* next;
}*start=NULL;
typedef struct node NODE;
void main()
{
int ch;
NODE *n_node,*temp;
lb:
clrscr();
printf("ntt******MENU******n");
printf("nttt1. PUSH");
printf("nttt2. POP");
printf("nttt3. Display");
printf("nttt4. Exit");
printf("nntEnter your choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1:
n_node=(NODE*)malloc(sizeof(NODE));
printf("ntEnter the elemenet to PUSH: ");
scanf("%d",&n_node->info);
n_node->next=start;
start=n_node;
break;
case 2:
if(start==NULL)
{
printf("ntStack is underflow.");
break;
}
temp=start->next;
printf("ntElelement POPed is : %d",start->info);
free(start);
start=temp;
break;
case 3:
temp=start;
printf("nnStack ementents are: ");
while(temp)
{
printf("nttt%d",temp->info);
temp=temp->next;
}
printf("ntttNULL");
break;
case 4:
exit(0);
default:
printf("ntaInvalid Choice!!");
}
getch();
goto lb;
}
Applications of Stack
 Prefix and Postfix Expressions:
 Prefix (Polish) Notation: Operators precede their operands. For
example, + 3 * 5 6 is equivalent to 3 + (5 * 6).
 Postfix (Reverse Polish) Notation: Operators follow their operands. For
example, 3 5 6 * + is equivalent to 3 + (5 * 6).
 Evaluation of Postfix Expressions:
 Use a stack to store operands.
 Scan the expression from left to right:
o If an operand is encountered, push it onto the stack.
o If an operator is encountered, pop the required number of
operands, perform the operation, and push the result back onto
the stack.
Iteration and Recursion
 Principles of Recursion:
 A recursive function calls itself.
 Must have a base case to stop the recursion.
 Can be direct (a function calls itself) or indirect (a function calls another
function which eventually calls the first function).
 Tail Recursion:
 A type of recursion where the recursive call is the last operation in the
function.
 Can be optimized by the compiler to avoid additional stack frames,
making it more efficient.
 Removing Recursion:
 Convert recursive algorithms into iterative ones using loops and, if
necessary, an explicit stack to simulate the call stack.
Problem Solving Using Iteration and Recursion
 Binary Search:
 Recursive: Divide the search interval in half and recursively search in
the appropriate half until the element is found or the interval is empty.
 Iterative: Use a loop to repeatedly divide the search interval in half and
adjust the interval based on comparisons.
 Fibonacci Numbers:
 Recursive: Compute the nth Fibonacci number by summing the (n-1)th
and (n-2)th Fibonacci numbers.
 Iterative: Use a loop to compute Fibonacci numbers up to the nth
number, storing only the last two computed values.
 Towers of Hanoi:
 A classic problem involving moving disks from one peg to another with
the help of an auxiliary peg, following specific rules.
 Recursive Solution: Move the top n-1 disks to the auxiliary peg, move
the nth disk to the target peg, and then move the n-1 disks from the
auxiliary peg to the target peg.
Key Points
 Stacks are used extensively in various applications such as expression
evaluation, function call management in programming languages (call stack),
and backtracking algorithms.
 Recursion simplifies the expression of some algorithms but can be less
efficient due to the overhead of multiple function calls.
 Iteration can be more efficient than recursion, especially for problems where
the depth of recursion is large or unbounded.
 Tail recursion is a specific form of recursion that can be optimized to avoid
additional stack usage, making it as efficient as iteration in some languages.
Queues: Operations on Queue: Create, Add, Delete, Full and
Empty, Circular queues, Array and linked implementation of queues
in C, Dequeue and Priority Queue.
Queues: Overview
Queue is a linear data structure that follows the First In, First Out (FIFO) principle.
It's similar to standing in a line at a ticket counter: the first person who enters the line
gets served first.
Basic Queue Operations
 Enqueue (Add): Adds an element to the rear (end) of the queue.
 Dequeue (Delete): Removes and returns the element from the front of the
queue.
 isEmpty: Checks if the queue is empty.
 isFull: Checks if the queue is full (applicable to fixed-size implementations).
Array Implementation of Queue
 Utilizes a fixed-size array to store elements.
 Uses two pointers (front and rear) to keep track of the position of the front and
rear elements.
 Elements are added at the rear and removed from the front.
 Circular array implementation is often used to utilize the entire array
efficiently.
Demo of Queue using Array Implementation
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int q[5],ch,i,front,rear;
front=rear=-1;
do
{
clrscr();
printf("nt********MENU**********n");
printf("ntt1. Insert");
printf("ntt2. Delete");
printf("ntt3. Display");
printf("ntt4. Exit");
lb:
printf("nntEnter your choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1:
if(rear==4)
{
printf("ntQueue is full!");
break;
}
if(front==-1)
front++;
printf("ntEnter element to Insert: ");
scanf("%d",&q[++rear]);
break;
case 2:
if(front==-1)
{
printf("ntQueue is empty!");
break;
}
printf("ntElement Deleted is: %d",q[front]);
if(front==rear)
front=rear=-1;
else
front++;
break;
MCA_Data Structure_Notes_of_UNIT_I & II.pdf
case 3:
if(front==-1)
{
printf("ntQueue is empty!");
break;
}
printf("ntQueue Elements are :");
for(i=front;i<=rear;i++)
printf(" %d",q[i]);
break;
case 4:
exit(0);
default:
printf("natInvalid choice!!");
goto lb;
}
getch();
}while(1);
}
Linked List Implementation of Queue
 Uses a linked list where each node contains data and a reference to the next
node.
 front and rear pointers point to the first and last nodes, respectively.
 Enqueue operations involve adding nodes at the rear, and dequeue
operations involve removing nodes from the front.
Demo of Queue using Linked List Implementation
#include <stdio.h>
#include <stdlib.h>
struct node
{
int info;
struct node* next;
}*start=NULL;
typedef struct node NODE;
void main()
{
int ch,a;
char c;
NODE *n_node,*temp;
lb:
clrscr();
printf("ntt******MENU******n");
printf("nttt1. Insert");
printf("nttt2. Delete");
printf("nttt3. Display");
printf("nttt4. Exit");
printf("nntEnter your choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1:
n_node=(NODE*)malloc(sizeof(NODE));
printf("ntEnter the elemenet to be insert: ");
scanf("%d",&n_node->info);
if(start==NULL)
{
n_node->next=start;
start=n_node;
}
else
{
temp=start;
while(temp->next)
temp=temp->next;
n_node->next=temp->next;
temp->next=n_node;
}
break;
case 2:
if(start==NULL)
{
printf("ntQueue is underflow.");
break;
}
temp=start->next;
printf("ntElement deleted is : %d",start->info);
free(start);
start=temp;
break;
case 3:
temp=start;
printf("ntQueue ementents are: ");
while(temp)
{
printf("%d->",temp->info);
temp=temp->next;
}
printf("NULL");
break;
case 4:
exit(0);
default:
printf("ntaInvalid Choice!!");
}
getch();
goto lb;
}
Circular Queues
 In a circular queue, when the rear reaches the end of the array, it wraps
around to the beginning, making the queue behave like a circle.
 This eliminates the need to shift elements when dequeuing and allows for
efficient space utilization.
 Care must be taken to handle full and empty conditions in circular queues
correctly.
Demo of Circular Queue using Array Implementation
#include <stdio.h>
#include <stdlib.h>
#define MAX 5
void main()
{
int cq[MAX],front,rear,i,ch,size;
size=0;
front=rear=-1;
lb:
clrscr();
printf("nttt******MENU******n");
printf("nttt1. Insert");
printf("nttt2. Delete");
printf("nttt3. Display");
printf("nttt4. Exit");
printf("nntEnter your choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1:
if (size==MAX)
printf("Queue is fulln");
else
{
if (front==-1)
front=0;
rear=(rear+1)%MAX;
printf("nEnter the element to be insert: ");
scanf("%d",&cq[rear]);
size++;
}
break;
case 2:
if (size==0)
printf("Queue is emptyn");
else
{
printf("nElement deleted is %d",cq[front]);
front=(front+1)%MAX;
size--;
if (size==0)
front=rear=-1;
}
}
break;
case 3:
if (size==0)
printf("Queue is emptyn");
else
{
printf("CQueue item are: ");
if(front<rear)
for(i=front;i<=rear;i++)
printf(" %d",cq[i]);
else
{
for(i=front;i<MAX;i++)
printf(" %d",cq[i]);
for(i=0;i<=rear;i++)
printf(" %d",cq[i]);
}
}
break;
case 4:
exit(0);
default:
printf("ntaInvalid Choice!!");
}
getch();
goto lb;
}
Dequeue (Double-Ended Queue)
 A deque is a queue that allows insertion and deletion of elements from both
the front and rear.
 It can serve as a queue, stack, or combination of both.
 Operations include insertFront, insertRear, deleteFront, deleteRear, getFront,
getRear, isEmpty, and isFull.
Priority Queue
 A priority queue is a type of queue where each element has a priority
associated with it.
 Elements are dequeued based on their priority, not the order in which they
were added.
 It can be implemented using arrays, linked lists, binary heaps, or other data
structures.
Key Points
 Queues are used in various applications such as CPU scheduling, breadth-
first search (BFS), and handling requests in web servers.
 Circular queues efficiently utilize space and avoid the shifting of elements.
 Deques offer more flexibility than queues by supporting insertion and deletion
at both ends.
 Priority queues prioritize elements based on their associated priorities,
allowing for efficient handling of tasks with varying importance.
Searching: Concept of Searching, Sequential search, Index
Sequential Search, Binary Search. Concept of Hashing & Collision
resolution Techniques used in Hashing.
Searching: Overview
Searching is the process of finding a specific element within a collection of data. It's
a fundamental operation in computer science and is used extensively in various
applications.
Sequential Search
 Sequential search, also known as linear search, involves iterating through
each element in a collection until the desired element is found.
 It is simple to implement and works on both sorted and unsorted collections.
 Time complexity: O(n) in the worst case, where n is the number of elements in
the collection.
Index Sequential Search
 Index sequential search is an enhancement of sequential search, primarily
used for large collections of data.
 It involves creating an index for the collection, which partitions the data into
smaller, manageable sections.
 This index allows for more efficient searching by narrowing down the search
space.
 Time complexity: O(n/k + k), where n is the number of elements and k is the
number of partitions.
Binary Search
 Binary search is an efficient searching algorithm applicable only to sorted
collections.
 It works by repeatedly dividing the search interval in half until the desired
element is found.
 It has a time complexity of O(log n), making it significantly faster than
sequential search for large collections.
Demo of Binary Search
#include<stdio.h>
#include<conio.h>
int bin_sr(int arr[],int size,int k)
{
int mid,left=0;
int right=size-1;
while (left<=right)
{
mid=(left+right)/2;
if (arr[mid]==k)
return mid;
if (arr[mid]<k)
left=mid+1;
else
right=mid-1;
}
return -1;
}
void main()
{
int arr[10],size,k,result,i;
clrscr();
printf("ntHow many no do you want to insert: ");
scanf("%d",&size);
printf("ntEnter array's elements in assending order: ");
for(i=0;i<size;i++)
scanf("%d",&arr[i]);
printf("ntEnter the element to be search: ");
scanf("%d",&k);
result=bin_sr(arr,size,k);
if (result!=-1)
printf("ntElement is present at index %dn", result);
else
printf("ntElement is not present in the arrayn");
getch();
}
Hashing
 Hashing is a technique used to map data of arbitrary size to fixed-size values
(hash codes) using a hash function.
 Hashing is commonly used for data retrieval in large collections, such as
databases, hash tables, and associative arrays.
 It provides constant-time average-case complexity for search, insert, and
delete operations, making it highly efficient.
Collision Resolution Techniques
 Collision occurs when two distinct keys hash to the same index in the hash
table.
 Various collision resolution techniques are used to handle collisions
effectively:
 Chaining: Each bucket in the hash table stores a linked list of
elements that hash to the same index.
 Open Addressing: Involves finding an alternate location in the hash
table when a collision occurs. Techniques include linear probing,
quadratic probing, and double hashing.
 Robin Hood Hashing: Similar to linear probing, but it tries to move
elements around to minimize the variance in probe lengths.
 Cuckoo Hashing: Utilizes multiple hash functions and two hash tables
to resolve collisions by rehashing keys to alternative locations.
Key Points
 Sequential search is simple but inefficient for large collections.
 Index sequential search improves efficiency by dividing the data into
partitions.
 Binary search is highly efficient but requires sorted data.
 Hashing provides constant-time average-case complexity for search, insert,
and delete operations.
 Collision resolution techniques are used to handle collisions effectively in
hash tables.
Ad

More Related Content

Similar to MCA_Data Structure_Notes_of_UNIT_I & II.pdf (20)

DS_PPT.pptx
DS_PPT.pptxDS_PPT.pptx
DS_PPT.pptx
MeghaKulkarni27
 
EC2311 – Data Structures and C Programming
EC2311 – Data Structures and C ProgrammingEC2311 – Data Structures and C Programming
EC2311 – Data Structures and C Programming
Padma Priya
 
intr_ds.ppt
intr_ds.pptintr_ds.ppt
intr_ds.ppt
PrakharNamdev3
 
Data Structures Mastery: Sample Paper for Practice"
Data Structures Mastery: Sample Paper for Practice"Data Structures Mastery: Sample Paper for Practice"
Data Structures Mastery: Sample Paper for Practice"
SaniyaGijoni
 
Data Structures using java notes for MCA
Data Structures using java notes for MCAData Structures using java notes for MCA
Data Structures using java notes for MCA
Arumugam90
 
Unit 1 introduction to data structure
Unit 1   introduction to data structureUnit 1   introduction to data structure
Unit 1 introduction to data structure
kalyanineve
 
Introduction to data structures and its types
Introduction to data structures and its typesIntroduction to data structures and its types
Introduction to data structures and its types
sonalishinge2015
 
Chapter 1 Introduction to Data Structures and Algorithms.pdf
Chapter 1 Introduction to Data Structures and Algorithms.pdfChapter 1 Introduction to Data Structures and Algorithms.pdf
Chapter 1 Introduction to Data Structures and Algorithms.pdf
Axmedcarb
 
DATA STRUCTURE AND ALGORITJM POWERPOINT.ppt
DATA STRUCTURE AND ALGORITJM POWERPOINT.pptDATA STRUCTURE AND ALGORITJM POWERPOINT.ppt
DATA STRUCTURE AND ALGORITJM POWERPOINT.ppt
yarotos643
 
19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity
Intro C# Book
 
Q
QQ
Q
guest9b2176
 
Data structures - Introduction
Data structures - IntroductionData structures - Introduction
Data structures - Introduction
DeepaThirumurugan
 
Bsc cs ii dfs u-1 introduction to data structure
Bsc cs ii dfs u-1 introduction to data structureBsc cs ii dfs u-1 introduction to data structure
Bsc cs ii dfs u-1 introduction to data structure
Rai University
 
1597380885789.ppt
1597380885789.ppt1597380885789.ppt
1597380885789.ppt
PraveenKumar977108
 
DATA STRUCTURE AND ALGORITHMS
DATA STRUCTURE AND ALGORITHMS DATA STRUCTURE AND ALGORITHMS
DATA STRUCTURE AND ALGORITHMS
removed_8057d320f6c8601c14a895598b86eacb
 
New open document text (2)
New open document text (2)New open document text (2)
New open document text (2)
Samron Samantha
 
Introduction to datastructures presentation
Introduction to datastructures presentationIntroduction to datastructures presentation
Introduction to datastructures presentation
krishkiran2408
 
Bca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structureBca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structure
Rai University
 
Introduction of C++ Text book UNIT-1 .ppt
Introduction of C++ Text book UNIT-1 .pptIntroduction of C++ Text book UNIT-1 .ppt
Introduction of C++ Text book UNIT-1 .ppt
akulaaruna81
 
Mca ii dfs u-1 introduction to data structure
Mca ii dfs u-1 introduction to data structureMca ii dfs u-1 introduction to data structure
Mca ii dfs u-1 introduction to data structure
Rai University
 
EC2311 – Data Structures and C Programming
EC2311 – Data Structures and C ProgrammingEC2311 – Data Structures and C Programming
EC2311 – Data Structures and C Programming
Padma Priya
 
Data Structures Mastery: Sample Paper for Practice"
Data Structures Mastery: Sample Paper for Practice"Data Structures Mastery: Sample Paper for Practice"
Data Structures Mastery: Sample Paper for Practice"
SaniyaGijoni
 
Data Structures using java notes for MCA
Data Structures using java notes for MCAData Structures using java notes for MCA
Data Structures using java notes for MCA
Arumugam90
 
Unit 1 introduction to data structure
Unit 1   introduction to data structureUnit 1   introduction to data structure
Unit 1 introduction to data structure
kalyanineve
 
Introduction to data structures and its types
Introduction to data structures and its typesIntroduction to data structures and its types
Introduction to data structures and its types
sonalishinge2015
 
Chapter 1 Introduction to Data Structures and Algorithms.pdf
Chapter 1 Introduction to Data Structures and Algorithms.pdfChapter 1 Introduction to Data Structures and Algorithms.pdf
Chapter 1 Introduction to Data Structures and Algorithms.pdf
Axmedcarb
 
DATA STRUCTURE AND ALGORITJM POWERPOINT.ppt
DATA STRUCTURE AND ALGORITJM POWERPOINT.pptDATA STRUCTURE AND ALGORITJM POWERPOINT.ppt
DATA STRUCTURE AND ALGORITJM POWERPOINT.ppt
yarotos643
 
19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity
Intro C# Book
 
Data structures - Introduction
Data structures - IntroductionData structures - Introduction
Data structures - Introduction
DeepaThirumurugan
 
Bsc cs ii dfs u-1 introduction to data structure
Bsc cs ii dfs u-1 introduction to data structureBsc cs ii dfs u-1 introduction to data structure
Bsc cs ii dfs u-1 introduction to data structure
Rai University
 
New open document text (2)
New open document text (2)New open document text (2)
New open document text (2)
Samron Samantha
 
Introduction to datastructures presentation
Introduction to datastructures presentationIntroduction to datastructures presentation
Introduction to datastructures presentation
krishkiran2408
 
Bca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structureBca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structure
Rai University
 
Introduction of C++ Text book UNIT-1 .ppt
Introduction of C++ Text book UNIT-1 .pptIntroduction of C++ Text book UNIT-1 .ppt
Introduction of C++ Text book UNIT-1 .ppt
akulaaruna81
 
Mca ii dfs u-1 introduction to data structure
Mca ii dfs u-1 introduction to data structureMca ii dfs u-1 introduction to data structure
Mca ii dfs u-1 introduction to data structure
Rai University
 

Recently uploaded (20)

CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
Political History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptxPolitical History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
Operations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdfOperations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdf
Arab Academy for Science, Technology and Maritime Transport
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
Ad

MCA_Data Structure_Notes_of_UNIT_I & II.pdf

  • 2. Introduction to data structure: Data, Entity, Information, Difference between Data and Information, Data type , Build in data type, Abstract data type, Definition of data structures, Types of Data Structures: Linear and Non-Linear Data Structure, Introduction to Algorithms: Definition of Algorithms, Difference between algorithm and programs, properties of algorithm, Algorithm Design Techniques, Performance Analysis of Algorithms, Complexity of various code structures, Order of Growth, Asymptotic Notations. Data, Entity, and Information  Data: Data refers to raw, unprocessed facts and figures without context. These can be numbers, characters, symbols, or even just bits of information that by themselves may not make sense. Data can be quantitative (numbers) or qualitative (descriptions).  Entity: An entity is an object or a thing that exists and can be distinctly identified. In databases, an entity is anything about which data can be collected, such as a person, place, event, or concept.  Information: Information is processed, organized, or structured data that is meaningful and useful for decision-making. When data is interpreted and presented in context, it becomes information. Difference between Data and Information  Data: Raw, unprocessed facts. For example, 123, John, and apple.  Information: Processed data that is meaningful and used for decision- making. For example, "John bought 3 apples." Data Type  Data Type: A data type is a classification that specifies which type of value a variable can hold and what operations can be performed on it. Common data types include integers, floating-point numbers, characters, and booleans.
  • 3. Built-in Data Types  Built-in Data Types: The basic data types provided by a programming language. Examples in many languages include:  Integer (int): Represents whole numbers.  Floating-point (float): Represents real numbers with fractional parts.  Character (char): Represents single characters.  Boolean (bool): Represents truth values (true or false). Abstract Data Type (ADT)  Abstract Data Type (ADT): A model for data structures that specifies the type of data stored, the operations supported on them, and the types of parameters of the operations. Examples include Stack, Queue, List, and Tree. Definition of Data Structures  Data Structures: A data structure is a way of organizing, managing, and storing data in a computer so that it can be accessed and modified efficiently. It defines the relationship between the data, the operations that can be performed on the data, and how the data can be manipulated. Examples include arrays, linked lists, stacks, queues, trees, and graphs. Types of Data Structures  Linear Data Structures: Elements are arranged in a sequential manner. Examples include:  Array: A collection of elements identified by index or key.  Linked List: A sequence of elements where each element points to the next one.  Stack: A collection of elements that follows Last in First out (LIFO) principle.  Queue: A collection of elements that follows First in First out (FIFO) principle.
  • 4.  Non-Linear Data Structures: Elements are not arranged in a sequential manner. Examples include:  Tree: A hierarchical structure with a root element and a collection of child elements.  Graph: A set of nodes (vertices) connected by edges. Introduction to Algorithms  Definition of Algorithms: An algorithm is a step-by-step procedure or formula for solving a problem. It is a sequence of instructions that are followed to perform a task or solve a problem. Difference between Algorithm and Program  Algorithm: A conceptual solution to a problem, expressed in terms of steps.  Program: A concrete implementation of an algorithm written in a specific programming language. Properties of Algorithm  Finiteness: The algorithm must terminate after a finite number of steps.  Definiteness: Each step must be precisely defined.  Input: An algorithm has zero or more inputs.  Output: An algorithm produces one or more outputs.  Effectiveness: Each step must be basic enough to be carried out, in principle, by a person using only paper and pencil. Algorithm Design Techniques  Divide and Conquer: Breaking the problem into smaller sub-problems, solving each sub-problem individually, and combining their solutions.  Dynamic Programming: Solving complex problems by breaking them into simpler sub-problems and storing the results of these sub-problems to avoid redundant work.  Greedy Algorithm: Making the locally optimal choice at each stage with the hope of finding a global optimum.
  • 5.  Backtracking: Trying out different solutions and abandoning them if they do not work.  Branch and Bound: Optimizing a solution by dividing it into sub-problems and pruning the ones that do not meet the criteria. Performance Analysis of Algorithms  Complexity of Various Code Structures: Evaluating the efficiency of algorithms in terms of time and space.  Time Complexity: How the execution time of an algorithm changes with the input size.  Space Complexity: How the memory usage of an algorithm changes with the input size. Order of Growth:  Describes the behavior of the complexity function as the input size grows.  Common orders of growth include constant (O(1)), logarithmic (O(log n)), linear (O(n)), linearithmic (O(n log n)), quadratic (O(n²)), cubic (O(n³)), and exponential (O(2^n)). Asymptotic Notations:  Big O (O): Upper bound of the complexity; worst-case scenario.  Omega (Ω): Lower bound of the complexity; best-case scenario.  Theta (Θ): Tight bound of the complexity; average-case scenario when both the upper and lower bounds are the same.
  • 6. Arrays: Definition, Single and Multidimensional Arrays, Representation of Arrays: Row Major Order, and Column Major Order, Derivation of Index Formulae for 1-D,2-D Array Application of arrays, Sparse Matrices and their representations. Arrays Definition: An array is a collection of elements, all of the same type, stored in contiguous memory locations. Each element is accessed by an index. Types of Arrays  Single-dimensional Arrays (1-D Arrays): A single-dimensional array is a linear sequence of elements, all of the same type. It is often referred to as a list.  Two-dimensional Arrays (2-D Arrays): These are like a table or a matrix with rows and columns.  Multidimensional Arrays: Multidimensional arrays are arrays of arrays. They can have two or more dimensions.  Higher-dimensional Arrays: These can be 3D, 4D, etc., and are used for more complex data structures. Demo of Single-dimensional Array #include<stdio.h> #include<conio.h> #include<stdlib.h> int i; void create(int[],int); void display(int ar[],int len); int search(int ar[],int len,int k); void insert(int ar[],int *len); void del(int ar[],int *len); void main() { int ar[10],size,ch,pos,k;
  • 7. do { clrscr(); printf("nt********MENU**********n"); printf("ntt1. Create"); printf("ntt2. Display"); printf("ntt3. Search"); printf("ntt4. Insert"); printf("ntt5. Delete"); printf("ntt6. Exit"); lb: printf("nntEnter your choice: "); scanf("%d",&ch); switch(ch) { case 1: printf("nHow many do you want to insert: "); scanf("%d",&size); create(ar,size); break; case 2: display(ar,size); break; case 3: printf("nEnter the value to be search: "); scanf("%d",&k); pos=search(ar,size,k); if(pos==-1) printf("nElement not found"); else printf("nElement found at %d position", pos+1); break; case 4: insert(ar,&size); break;
  • 8. case 5: del(ar,&size); break; case 6: exit(0); default: printf("naInvalid choice!!"); goto lb; } getch(); }while(1); } void create(int ar[],int len) { printf("nEnter %d elements of array: ",len); for(i=0;i<len;i++) scanf("%d",&ar[i]); } void display(int ar[],int len) { if(len<0 || len>10) { printf("ntaFirst create the array!"); getch(); return; } printf("nArray's elements are as follows: "); for(i=0;i<len;i++) printf(" %d",ar[i]); } int search(int ar[],int len,int k) { for(i=0;i<len;i++) if(ar[i]==k) return(i); return(-1); }
  • 9. void insert(int ar[],int *len) { int k,pos; printf("nEnter the value after which insertion is required: "); scanf("%d",&k); pos=search(ar,*len,k); if(pos==-1) { printf("nElement not found"); return; } for(i=*len;i>pos;i--) ar[i]=ar[i-1]; printf("nEnter the value to be insert: "); scanf("%d",&ar[pos+1]); *len+=1; } void del(int ar[],int *len) { int k,pos; printf("nEnter the value to be delete: "); scanf("%d",&k); pos=search(ar,*len,k); if(pos==-1) { printf("nElement not found"); return; } for(i=pos;i<*len;i++) ar[i]=ar[i+1]; *len-=1; }
  • 10. Demo of Two-dimensional Array #include<stdio.h> #include<conio.h> #include<stdlib.h> int i,j,k; void get_mat(int x[][10],int r,int c); void dis_mat(int x[][10],int r,int c); void main() { int a[10][10],b[10][10],c[10][10],r1,c1,r2,c2; lb: clrscr(); printf("nEnter the dimention of first mattrix (RxC): "); scanf("%d%d",&r1,&c1); printf("nEnter the dimention of second mattrix (RxC): "); scanf("%d%d",&r2,&c2); if(c1!=r2) { printf("nMattrix are not compatible!"); printf("nPress any key to try again...."); goto lb; } printf("nEnter the elements of first mattrix: "); get_mat(a,r1,c1); printf("nThe first mattrix is as follows:n"); dis_mat(a,r1,c1); printf("nEnter the elements of second mattrix: "); get_mat(b,r2,c2); printf("nThe second mattrix is as follows:n"); dis_mat(b,r2,c2); for(i=0;i<r1;i++) for(j=0;j<c2;j++) { c[i][j]=0; for(k=0;k<c1;k++) c[i][j]+=a[i][k]*b[k][j]; }
  • 11. printf("nMultipication of Mattrix are as follows:n"); dis_mat(c,r1,c2); getch(); } void get_mat(int x[][10],int r,int c) { for(i=0;i<r;i++) for(j=0;j<c;j++) scanf("%d",&x[i][j]); } void dis_mat(int x[][10],int r,int c) { for(i=0;i<r;i++) { for(j=0;j<c;j++) printf(" %d ",x[i][j]); printf("n"); } } Representation of Arrays  Row Major Order: In row major order, the elements of a multi-dimensional array are stored row by row. For example, in a 2-D array, the first row is stored in contiguous memory locations, followed by the second row, and so on.  Column Major Order: In column major order, the elements of a multi- dimensional array are stored column by column. For example, in a 2-D array, the first column is stored in contiguous memory locations, followed by the second column, and so on. Derivation of Index Formulae  1-D Array: The index formula for accessing the ith element of a 1-D array A with base address B is: Address(𝐴[𝑖])=𝐵+𝑖× size_of_each_element
  • 12.  2-D Array: For a 2-D array A with m rows and n columns, the element at position (𝑖,𝑗) can be accessed using the following formulas:  Row Major Order: Address(𝐴[𝑖][𝑗])=𝐵+((𝑖×𝑛)+𝑗)×w  Column Major Order: Address(𝐴[𝑖][𝑗])=𝐵+((𝑗×𝑚)+𝑖)×w Where: o B is the base address of the array. o i and j are the row and column indices, respectively. o n is the total number of columns in the array. o m is the total number of rows in the array. o w is the size of each element Applications of Arrays  Storing and accessing sequential data: Arrays are used to store a sequence of elements which can be accessed by an index.  Matrix operations: Arrays are used in mathematical computations, especially matrices.  Buffers in Input/Output operations: Arrays are used to store data temporarily during I/O operations.  Implementing data structures: Arrays are fundamental in implementing other data structures like stacks, queues, and heaps.  Image processing: Pixels of an image are stored in 2-D arrays. Sparse Matrices and Their Representations  Sparse Matrix: A sparse matrix is a matrix in which most of the elements are zero. Efficient storage techniques are used to save space and reduce computational complexity.
  • 13. Linked lists: Array Implementation and Pointer Implementation of Singly Linked Lists, Doubly Linked List, Circularly Linked List, Operations on a Linked List. Insertion, Deletion, Traversal, Polynomial Representation and Addition Subtraction & Multiplications of Single variable. Linked List Overview A linked list is a linear data structure where elements, called nodes, are not stored in contiguous memory locations. Each node contains two parts:  Data: Stores the value.  Pointer (or Reference): Points to the next node in the sequence. Types of Linked Lists  Singly Linked Lists A singly linked list is a data structure consisting of nodes where each node contains data and a reference (or pointer) to the next node in the sequence. Node Structure: struct Node { int data; Node* next; };  Doubly Linked Lists A doubly linked list is a data structure consisting of nodes where each node contains data, a reference to the next node, and a reference to the previous node. Node Structure: struct Node { int data; Node* next; * prev; };
  • 14.  Circularly Linked Lists A circularly linked list is a data structure where the last node points to the first node, forming a circle. It can be either singly or doubly linked. Singly Circularly Linked List Node Structure: struct Node { int data; Node* next; }; Basic Operations  Insertion:  At the beginning: o Update the new node's next pointer to the current head. o Update the head to the new node.  At the end: o Traverse to the last node. o Update the last node's next pointer to the new node. o Update the new node's next pointer to null (or the head in circular lists).  At a given position: o Traverse to the node before the desired position. o Update the new node's next pointer to the current node's next pointer. o Update the current node's next pointer to the new node.  Deletion:  From the beginning: o Update the head to the next node. o Free the old head node.  From the end: o Traverse to the second last node. o Update its next pointer to null. o Free the last node.
  • 15.  From a given position: o Traverse to the node before the desired position. o Update its next pointer to the next node's next pointer. o Free the node at the given position.  Traversal: Start from the head and follow the next pointers until reaching the end (null for singly linked lists, the head for circular linked lists). Demo of Singly Linked Lists #include <stdio.h> #include <stdlib.h> struct node { int info; struct node* next; }*start=NULL; typedef struct node NODE; void main() { int ch,a; char c; NODE *n_node,*temp,*before,*after; lb: clrscr(); printf("ntt******MENU******n"); printf("nttt1. Create"); printf("nttt2. Display"); printf("nttt3. Insertion start"); printf("nttt4. Insertion mid"); printf("nttt5. Deletion"); printf("nttt6. Exit"); printf("nntEnter your choice: "); scanf("%d",&ch);
  • 16. switch(ch) { case 1: do { n_node=(NODE*)malloc(sizeof(NODE)); printf("ntEnter the elemenet: "); scanf("%d",&n_node->info); if(start==NULL) { n_node->next=start; start=n_node; } else { temp=start; while(temp->next) temp=temp->next; n_node->next=temp->next; temp->next=n_node; } printf("ntWant to enter more element (y/n): "); fflush(stdin); scanf("%c",&c); }while(c=='Y'||c=='y'); break; case 2: temp=start; printf("ntList ementents are: "); while(temp) { printf("%d->",temp->info); temp=temp->next; } printf("NULL"); break;
  • 17. case 3: n_node=(NODE*)malloc(sizeof(NODE)); printf("ntEnter the elemenet to be insert: "); scanf("%d",&n_node->info); n_node->next=start; start=n_node; break; case 4: n_node=(NODE*)malloc(sizeof(NODE)); printf("ntEnter the elemenet to be insert: "); scanf("%d",&n_node->info); printf("ntEnter the elemenet after which insertion is required: "); scanf("%d",&a); temp=start; while(temp) { if(temp->info==a) break; temp=temp->next; } if(temp==NULL) { printf("ntElement not found."); break; } n_node->next=temp->next; temp->next=n_node; break; case 5: printf("ntEnter the element to be delete: "); scanf("%d",&a); if(start->info==a) { temp=start->next; free(start); start=temp;
  • 18. break; } before=start; while(before) { if(before->next->info==a) break; before=before->next; } if(before==NULL) { printf("ntElement not found."); break; } temp=before->next; after=temp->next; before->next=after; free(temp); break; case 6: exit(0); default: printf("ntaInvalid Choice!!"); } getch(); goto lb; } Demo of Doubly Linked Lists #include <stdio.h> #include <stdlib.h> struct node { int info; struct node* next,*prev; }*start=NULL;
  • 19. typedef struct node NODE; void main() { int ch,a; char c; NODE *n_node,*temp,*before,*after; lb: clrscr(); printf("ntt******MENU******n"); printf("nttt1. Create"); printf("nttt2. Display"); printf("nttt3. Insertion start"); printf("nttt4. Insertion mid"); printf("nttt5. Deletion"); printf("nttt6. Exit"); printf("nntEnter your choice: "); scanf("%d",&ch); switch(ch) { case 1: do { n_node=(NODE*)malloc(sizeof(NODE)); printf("ntEnter the elemenet: "); scanf("%d",&n_node->info); if(start==NULL) { n_node->next=start; start=n_node; } else { temp=start; while(temp->next) temp=temp->next;
  • 20. n_node->next=temp->next; n_node->prev=temp; temp->next=n_node; } printf("ntWant to enter more element (y/n): "); fflush(stdin); scanf("%c",&c); }while(c=='Y'||c=='y'); break; case 2: temp=start; printf("ntList ementents are: "); while(temp) { printf("%d->",temp->info); temp=temp->next; } printf("NULL"); break; case 3: n_node=(NODE*)malloc(sizeof(NODE)); printf("ntEnter the elemenet to be insert: "); scanf("%d",&n_node->info); n_node->next=start; start->prev=n_node; start=n_node; break; case 4: n_node=(NODE*)malloc(sizeof(NODE)); printf("ntEnter the elemenet to be insert: "); scanf("%d",&n_node->info); printf("ntEnter the elemenet after which insertion is required: "); scanf("%d",&a); before=start; while(before) {
  • 21. if(before->info==a) break; before=before->next; } if(before==NULL) { printf("ntElement not found."); break; } after=before->next; n_node->next=after; after->prev=n_node; before->next=n_node; n_node->prev=before; break; case 5: printf("ntEnter the element to be delete: "); scanf("%d",&a); if(start->info==a) { temp=start->next; free(start); start=temp; break; } before=start; while(before) { if(before->next->info==a) break; before=before->next; } if(before==NULL) { printf("ntElement not found."); break; }
  • 22. temp=before->next; after=temp->next; before->next=after; after->prev=before; free(temp); break; case 6: exit(0); default: printf("ntaInvalid Choice!!"); } getch(); goto lb; } Advantages of Linked Lists  Dynamic Size: Can grow or shrink in size as needed.  Efficient Insertions/Deletions: Insertion and deletion operations are efficient, particularly when dealing with large datasets. Disadvantages of Linked Lists  Memory Usage: Requires extra memory for storing pointers.  No Random Access: Accessing elements by index requires traversing from the head. Use Cases  Dynamic Data: Useful when the size of the data is not known beforehand and needs frequent insertions/deletions.  Real-Time Systems: Where low latency for insertion/deletion is crucial.  Implementing Other Data Structures: Such as stacks, queues, and associative arrays.
  • 23. Variants and Applications  Stack: Implemented using singly linked lists with insertion and deletion at the head.  Queue: Implemented using singly linked lists with insertion at the end and deletion at the head.  Doubly Linked List Applications: Useful in scenarios where bidirectional traversal is required, such as in navigation systems.  Circular Linked List Applications: Useful in applications that need a cyclic iteration, such as round-robin scheduling. Polynomial Representation Using Linked Lists Polynomials can be efficiently represented using linked lists where each node stores the coefficient and exponent of a term. Node Structure: struct Node { int coeff,exp; Node* next; };  Polynomial Addition:  Traverse both polynomials, adding terms with the same exponents and creating new nodes for terms with unique exponents.  Polynomial Multiplication:  Multiply each term of the first polynomial with each term of the second polynomial.  Combine like terms and create a new polynomial.
  • 25. Stacks: Abstract Data Type, Primitive Stack operations: Push & Pop, Array and Linked Implementation of Stack in C, Application of stack: Prefix and Postfix Expressions, Evaluation of postfix expression, Iteration and Recursion- Principles of recursion, Tail recursion, Removal of recursion Problem solving using iteration and recursion with examples such as binary search, Fibonacci numbers, and Hanoi towers. Stacks: Abstract Data Type Stack is a linear data structure that follows the Last In, First Out (LIFO) principle. In this structure, the most recently added element is the first one to be removed. The basic operations for a stack include:  Push: Add an element to the top of the stack.  Pop: Remove and return the element from the top of the stack.  isEmpty: Check if the stack is empty.  isFull: Check if the stack is full (in case of a fixed-size stack). Array and Linked List Implementation of Stack  Array Implementation:  Utilizes a fixed-size array.  A variable (top) keeps track of the index of the top element.  Advantages: Simple and efficient for small datasets.  Disadvantages: Fixed size, requires resizing if the stack grows beyond its initial capacity. Demo of Stack using Array Implementation #include<stdio.h> #include<conio.h> #include<stdlib.h> void main() { int s[5],ch,i,tos=-1;
  • 26. do { clrscr(); printf("nt********MENU**********n"); printf("ntt1. PUSH"); printf("ntt2. POP"); printf("ntt3. Display"); printf("ntt4. Exit"); lb: printf("nntEnter your choice: "); scanf("%d",&ch); switch(ch) { case 1: if(tos==4) { printf("ntStack is overflow!"); break; } printf("ntEnter element to PUSH: "); scanf("%d",&s[++tos]); break; case 2: if(tos==-1) { printf("ntStack is underflow!"); break; } printf("ntElement POPPed is: %d",s[tos--]); break; case 3: if(tos==-1) { printf("ntStack is underflow!"); break; } printf("ntStack Elements are :");
  • 27. for(i=tos;i>=0;i--) printf("ntttt%d",s[i]); break; case 4: exit(0); default: printf("natInvalid choice!!"); goto lb; } getch(); }while(1); }  Linked List Implementation:  Each element is a node containing data and a reference to the next node.  A pointer (top) points to the most recently added node.  Advantages: Dynamic size, no need for resizing.  Disadvantages: More complex memory management due to dynamic allocation. Demo of Stack using Linked List Implementation #include <stdio.h> #include <stdlib.h> struct node { int info; struct node* next; }*start=NULL; typedef struct node NODE; void main() { int ch; NODE *n_node,*temp; lb:
  • 28. clrscr(); printf("ntt******MENU******n"); printf("nttt1. PUSH"); printf("nttt2. POP"); printf("nttt3. Display"); printf("nttt4. Exit"); printf("nntEnter your choice: "); scanf("%d",&ch); switch(ch) { case 1: n_node=(NODE*)malloc(sizeof(NODE)); printf("ntEnter the elemenet to PUSH: "); scanf("%d",&n_node->info); n_node->next=start; start=n_node; break; case 2: if(start==NULL) { printf("ntStack is underflow."); break; } temp=start->next; printf("ntElelement POPed is : %d",start->info); free(start); start=temp; break; case 3: temp=start; printf("nnStack ementents are: "); while(temp) { printf("nttt%d",temp->info); temp=temp->next; } printf("ntttNULL");
  • 29. break; case 4: exit(0); default: printf("ntaInvalid Choice!!"); } getch(); goto lb; } Applications of Stack  Prefix and Postfix Expressions:  Prefix (Polish) Notation: Operators precede their operands. For example, + 3 * 5 6 is equivalent to 3 + (5 * 6).  Postfix (Reverse Polish) Notation: Operators follow their operands. For example, 3 5 6 * + is equivalent to 3 + (5 * 6).  Evaluation of Postfix Expressions:  Use a stack to store operands.  Scan the expression from left to right: o If an operand is encountered, push it onto the stack. o If an operator is encountered, pop the required number of operands, perform the operation, and push the result back onto the stack. Iteration and Recursion  Principles of Recursion:  A recursive function calls itself.  Must have a base case to stop the recursion.  Can be direct (a function calls itself) or indirect (a function calls another function which eventually calls the first function).  Tail Recursion:  A type of recursion where the recursive call is the last operation in the function.
  • 30.  Can be optimized by the compiler to avoid additional stack frames, making it more efficient.  Removing Recursion:  Convert recursive algorithms into iterative ones using loops and, if necessary, an explicit stack to simulate the call stack. Problem Solving Using Iteration and Recursion  Binary Search:  Recursive: Divide the search interval in half and recursively search in the appropriate half until the element is found or the interval is empty.  Iterative: Use a loop to repeatedly divide the search interval in half and adjust the interval based on comparisons.  Fibonacci Numbers:  Recursive: Compute the nth Fibonacci number by summing the (n-1)th and (n-2)th Fibonacci numbers.  Iterative: Use a loop to compute Fibonacci numbers up to the nth number, storing only the last two computed values.  Towers of Hanoi:  A classic problem involving moving disks from one peg to another with the help of an auxiliary peg, following specific rules.  Recursive Solution: Move the top n-1 disks to the auxiliary peg, move the nth disk to the target peg, and then move the n-1 disks from the auxiliary peg to the target peg. Key Points  Stacks are used extensively in various applications such as expression evaluation, function call management in programming languages (call stack), and backtracking algorithms.  Recursion simplifies the expression of some algorithms but can be less efficient due to the overhead of multiple function calls.  Iteration can be more efficient than recursion, especially for problems where the depth of recursion is large or unbounded.
  • 31.  Tail recursion is a specific form of recursion that can be optimized to avoid additional stack usage, making it as efficient as iteration in some languages.
  • 32. Queues: Operations on Queue: Create, Add, Delete, Full and Empty, Circular queues, Array and linked implementation of queues in C, Dequeue and Priority Queue. Queues: Overview Queue is a linear data structure that follows the First In, First Out (FIFO) principle. It's similar to standing in a line at a ticket counter: the first person who enters the line gets served first. Basic Queue Operations  Enqueue (Add): Adds an element to the rear (end) of the queue.  Dequeue (Delete): Removes and returns the element from the front of the queue.  isEmpty: Checks if the queue is empty.  isFull: Checks if the queue is full (applicable to fixed-size implementations). Array Implementation of Queue  Utilizes a fixed-size array to store elements.  Uses two pointers (front and rear) to keep track of the position of the front and rear elements.  Elements are added at the rear and removed from the front.  Circular array implementation is often used to utilize the entire array efficiently. Demo of Queue using Array Implementation #include<stdio.h> #include<conio.h> #include<stdlib.h> void main() { int q[5],ch,i,front,rear; front=rear=-1;
  • 33. do { clrscr(); printf("nt********MENU**********n"); printf("ntt1. Insert"); printf("ntt2. Delete"); printf("ntt3. Display"); printf("ntt4. Exit"); lb: printf("nntEnter your choice: "); scanf("%d",&ch); switch(ch) { case 1: if(rear==4) { printf("ntQueue is full!"); break; } if(front==-1) front++; printf("ntEnter element to Insert: "); scanf("%d",&q[++rear]); break; case 2: if(front==-1) { printf("ntQueue is empty!"); break; } printf("ntElement Deleted is: %d",q[front]); if(front==rear) front=rear=-1; else front++; break;
  • 35. case 3: if(front==-1) { printf("ntQueue is empty!"); break; } printf("ntQueue Elements are :"); for(i=front;i<=rear;i++) printf(" %d",q[i]); break; case 4: exit(0); default: printf("natInvalid choice!!"); goto lb; } getch(); }while(1); } Linked List Implementation of Queue  Uses a linked list where each node contains data and a reference to the next node.  front and rear pointers point to the first and last nodes, respectively.  Enqueue operations involve adding nodes at the rear, and dequeue operations involve removing nodes from the front. Demo of Queue using Linked List Implementation #include <stdio.h> #include <stdlib.h> struct node { int info; struct node* next; }*start=NULL;
  • 36. typedef struct node NODE; void main() { int ch,a; char c; NODE *n_node,*temp; lb: clrscr(); printf("ntt******MENU******n"); printf("nttt1. Insert"); printf("nttt2. Delete"); printf("nttt3. Display"); printf("nttt4. Exit"); printf("nntEnter your choice: "); scanf("%d",&ch); switch(ch) { case 1: n_node=(NODE*)malloc(sizeof(NODE)); printf("ntEnter the elemenet to be insert: "); scanf("%d",&n_node->info); if(start==NULL) { n_node->next=start; start=n_node; } else { temp=start; while(temp->next) temp=temp->next; n_node->next=temp->next; temp->next=n_node; } break;
  • 37. case 2: if(start==NULL) { printf("ntQueue is underflow."); break; } temp=start->next; printf("ntElement deleted is : %d",start->info); free(start); start=temp; break; case 3: temp=start; printf("ntQueue ementents are: "); while(temp) { printf("%d->",temp->info); temp=temp->next; } printf("NULL"); break; case 4: exit(0); default: printf("ntaInvalid Choice!!"); } getch(); goto lb; } Circular Queues  In a circular queue, when the rear reaches the end of the array, it wraps around to the beginning, making the queue behave like a circle.  This eliminates the need to shift elements when dequeuing and allows for efficient space utilization.
  • 38.  Care must be taken to handle full and empty conditions in circular queues correctly. Demo of Circular Queue using Array Implementation #include <stdio.h> #include <stdlib.h> #define MAX 5 void main() { int cq[MAX],front,rear,i,ch,size; size=0; front=rear=-1; lb: clrscr(); printf("nttt******MENU******n"); printf("nttt1. Insert"); printf("nttt2. Delete"); printf("nttt3. Display"); printf("nttt4. Exit"); printf("nntEnter your choice: "); scanf("%d",&ch); switch(ch) { case 1: if (size==MAX) printf("Queue is fulln"); else { if (front==-1) front=0; rear=(rear+1)%MAX; printf("nEnter the element to be insert: "); scanf("%d",&cq[rear]); size++; } break;
  • 39. case 2: if (size==0) printf("Queue is emptyn"); else { printf("nElement deleted is %d",cq[front]); front=(front+1)%MAX; size--; if (size==0) front=rear=-1; } } break; case 3: if (size==0) printf("Queue is emptyn"); else { printf("CQueue item are: "); if(front<rear) for(i=front;i<=rear;i++) printf(" %d",cq[i]); else { for(i=front;i<MAX;i++) printf(" %d",cq[i]); for(i=0;i<=rear;i++) printf(" %d",cq[i]); } } break; case 4: exit(0); default: printf("ntaInvalid Choice!!"); } getch();
  • 40. goto lb; } Dequeue (Double-Ended Queue)  A deque is a queue that allows insertion and deletion of elements from both the front and rear.  It can serve as a queue, stack, or combination of both.  Operations include insertFront, insertRear, deleteFront, deleteRear, getFront, getRear, isEmpty, and isFull. Priority Queue  A priority queue is a type of queue where each element has a priority associated with it.  Elements are dequeued based on their priority, not the order in which they were added.  It can be implemented using arrays, linked lists, binary heaps, or other data structures. Key Points  Queues are used in various applications such as CPU scheduling, breadth- first search (BFS), and handling requests in web servers.  Circular queues efficiently utilize space and avoid the shifting of elements.  Deques offer more flexibility than queues by supporting insertion and deletion at both ends.  Priority queues prioritize elements based on their associated priorities, allowing for efficient handling of tasks with varying importance.
  • 41. Searching: Concept of Searching, Sequential search, Index Sequential Search, Binary Search. Concept of Hashing & Collision resolution Techniques used in Hashing. Searching: Overview Searching is the process of finding a specific element within a collection of data. It's a fundamental operation in computer science and is used extensively in various applications. Sequential Search  Sequential search, also known as linear search, involves iterating through each element in a collection until the desired element is found.  It is simple to implement and works on both sorted and unsorted collections.  Time complexity: O(n) in the worst case, where n is the number of elements in the collection. Index Sequential Search  Index sequential search is an enhancement of sequential search, primarily used for large collections of data.  It involves creating an index for the collection, which partitions the data into smaller, manageable sections.  This index allows for more efficient searching by narrowing down the search space.  Time complexity: O(n/k + k), where n is the number of elements and k is the number of partitions. Binary Search  Binary search is an efficient searching algorithm applicable only to sorted collections.  It works by repeatedly dividing the search interval in half until the desired element is found.  It has a time complexity of O(log n), making it significantly faster than sequential search for large collections.
  • 42. Demo of Binary Search #include<stdio.h> #include<conio.h> int bin_sr(int arr[],int size,int k) { int mid,left=0; int right=size-1; while (left<=right) { mid=(left+right)/2; if (arr[mid]==k) return mid; if (arr[mid]<k) left=mid+1; else right=mid-1; } return -1; } void main() { int arr[10],size,k,result,i; clrscr(); printf("ntHow many no do you want to insert: "); scanf("%d",&size); printf("ntEnter array's elements in assending order: "); for(i=0;i<size;i++) scanf("%d",&arr[i]); printf("ntEnter the element to be search: "); scanf("%d",&k); result=bin_sr(arr,size,k); if (result!=-1) printf("ntElement is present at index %dn", result); else printf("ntElement is not present in the arrayn");
  • 43. getch(); } Hashing  Hashing is a technique used to map data of arbitrary size to fixed-size values (hash codes) using a hash function.  Hashing is commonly used for data retrieval in large collections, such as databases, hash tables, and associative arrays.  It provides constant-time average-case complexity for search, insert, and delete operations, making it highly efficient. Collision Resolution Techniques  Collision occurs when two distinct keys hash to the same index in the hash table.  Various collision resolution techniques are used to handle collisions effectively:  Chaining: Each bucket in the hash table stores a linked list of elements that hash to the same index.  Open Addressing: Involves finding an alternate location in the hash table when a collision occurs. Techniques include linear probing, quadratic probing, and double hashing.  Robin Hood Hashing: Similar to linear probing, but it tries to move elements around to minimize the variance in probe lengths.  Cuckoo Hashing: Utilizes multiple hash functions and two hash tables to resolve collisions by rehashing keys to alternative locations. Key Points  Sequential search is simple but inefficient for large collections.  Index sequential search improves efficiency by dividing the data into partitions.  Binary search is highly efficient but requires sorted data.
  • 44.  Hashing provides constant-time average-case complexity for search, insert, and delete operations.  Collision resolution techniques are used to handle collisions effectively in hash tables.