0% found this document useful (0 votes)
13 views

dsa All

The document provides an overview of data structures and algorithms, detailing their definitions, types, complexities, and operations. It explains the importance of data structures in organizing and processing data efficiently, as well as various algorithm complexities such as time and space. Additionally, it covers specific data structures like arrays, linked lists, and their operations, along with concepts like time-space trade-offs and abstract data types.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

dsa All

The document provides an overview of data structures and algorithms, detailing their definitions, types, complexities, and operations. It explains the importance of data structures in organizing and processing data efficiently, as well as various algorithm complexities such as time and space. Additionally, it covers specific data structures like arrays, linked lists, and their operations, along with concepts like time-space trade-offs and abstract data types.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Data structure  Way of analyzing an algorithm --

1.Best case 2. Average case 3. Worst case


 Data Structure is a branch of Computer Science.  Complexity of an algorithm --
 A data structure is a storage that is used to store and organize  Complexity in algorithms refers to the amount of
all the data items. resources required to solve a problem or perform a task.
 used for processing, retrieving, and storing data.  Resources may be me and space.
 Types of Complexi es of an algorithm --
Why do we use data structure
 Time complexity of an algorithm is the amount of me
 Necessary for designing efficient algorithms. it needs to run to comple on.
 It helps to organization of all data items within the memory.  Space complexity of an algorithm is the amount of
 It requires less time. space it needs to run to comple on.
 Easy access to the large database.
 order of Complexity of an algorithm --
Classification/ Types of Data structure
O(1) < O(logn) < O(n) < O(nlogn) < O(n^2) < O(n^3) < O(2^n) < O(3^n) < O(n!)
 Linear data structure --allows data elements to be arranged
Asymptotic Notation
in a sequen al or linear fashion.
Example: arrays, linked lists, stack, and queue etc. It is used to write possible running me for an algorithm.It also
 Non-Linear data structure -- It is a form of data structure referred to as 'best case' and 'worst case' scenarios respec vely.
where the data elements do not stay arranged linearly or
sequen ally.  Big-oh nota on:
Example: Tree, graph etc.  It is the method of expressing the upper bound of an
algorithm's running me.
Terminologies in Data structure  It is the measure of the longest amount of me. The
func on f (n) = O (g (n))
 Data -- Data are values or set of values.  f(n) <= c.g(n) where n>n0
 Data Item -- Data item refers to single unit of values.  Example: 3n+2=O(n) as 3n+2≤4n for all n≥2
 En ty -- An en ty is that which contains certain a ributes or
proper es, which may be assigned values.
 En ty Set -- En es of similar a ributes form an en ty set.
 Field -- Field is a single elementary unit of informa on
represen ng an a ribute of an en ty.
 Record -- Record is a collec on of field values of a given
en ty.
 File -- File is a collec on of records of the en es in a given
en ty set.  Big-Omega nota on:
Datatypes in C programming  It is the method of expressing the lower bound of an
algorithm's running me.
 Primi ve Data Types – It is the most basic data types that  It is the measure of the smallest amount of me. The
are used for represen ng simple values such as: func on f (n) = Ω(g (n))
 Integers – 23, 33432 ,342342 etc.  f(n) >= c.g(n) where n>n0
 Float – 23.2342, 232.00,2342.0000,323.323 etc.  Example: 3n-3= Ω (n) as 3n-3 >=2n for all n≥3
 Characters - ‘2’, ‘a, ‘$’, ‘@,’g’ etc.
 Void – used to specify the type of func ons which
returns nothing.
 Non-Primi ve Data Types – It is derived from primi ve data
types.
 Arrays
 Linked-list  Theta(Θ) nota on:
 Queue  It is the method of expressing the both lower and upper
 Stack etc. bound of an algorithm's running me.
 It is the measure of the average amount of me. The
Algorithm func on f (n) = Θ(g (n))
 c1.g(n) <= f(n) <= c2.g(n) where n>n0
 An algorithm is a step-by-step procedure of any problem.
 Example: 3n-3=O(n) as 2n<= 3n-3 <= 4n for all n≥3
 Criteria of an algorithm --
1. Input 2. Output 3. Definiteness 4. Finiteness 5.
Effec veness
 It is used to implement vectors, and lists in C++ STL.
 Arrays are used as the base of all sor ng algorithms.
 It is used to implement other DS like stack, queue, etc.
 Used for implemen ng matrices.
 Graphs are also implemented as arrays in the form of an
adjacency matrix etc.

Sparse Matrix
Time-Space Trade-Off in Algorithms
 It is matrix in which most of the elements of the matrix have
 It is a problem solving technique in which we solve the zero value .
problem:  Only we stored non-zero elements with triples- (Row,
 Either in less me and using more space, or Column, value).
 In very li le space by spending more me.  Array representa on of Sparse Matrix –
 The best algorithm is that which helps to solve a problem
that requires less space in memory as well as takes less me
to generate the output.
 it is not always possible to achieve both of these condi ons
at the same me.

Abstract Data type (ADT)  Linked list representa on of sparse matrix –

 It is a type (or class) for objects whose behaviour is defined


by a set of values and a set of opera ons.
 The defini on of ADT only men ons what opera ons are to
be performed but not how these opera ons will be
implemented.
Linked List
 Example : if we talk about LIST then here we can store
mul ple value and it has many built in func on so that we  A linked list is a collec on of “nodes” connected together via
will work on that data . links.
Func on such as insert(), delete(), pop(), remove() etc.  These nodes consist of the data to be stored and a pointer to
the address of the next element .
Array
 Linked list has mul ple types:
 An array is a collec on of items stored at con guous 1. singly linked list 2. Doubly linked list 3. Circular linked list
memory loca ons.
Singly Linked List (SLL)
 Array is linear data structure. It is one of the simplest DS.
 The idea is to store mul ple items of the same type  It is a linear data structure in which the elements are not
together. stored in contiguous memory locations .
 Syntax -- type variable_name [size];  Each element is connected only to its next element using
 Example – int arr[10]; this is a array declara on of the array address.
now here we can only store 10 integer values in this array
 Array has two type:

1. One dimensional 2. Mul dimensional  Representa on Node of SLL :


 One dimensional Array :
struct node{
 Array represented as one-one dimension such as row or
int data; //data item for storing value of the node
column and that holds finite number of same type of
struct node *next; //address of the next node
data items is called 1D array .
};
 Example -- int arr[10];
 create Node of SLL:
 Mul -dimensional Array :
 Array represented as more than one dimension . there struct Node* Node(int data){
are no restric on to number of dimensions that we can struct Node* newNode=(struct Node*)malloc(sizeof(struct
Node ));
have.
newNode->data=data;
 Example -- int arr[2][4][5]; newNode->next=NULL;
 Applica on of Array : return newNode;
 Arrays can be storing data in tabular format }
Operations on SLL  Traverse Linked List:

 Insert At beginning : void traverse(struct Node* head){


while (head->next!=NULL){
struct Node * addAtBeg(int data, struct Node* head){ printf("%d ", head->data);
struct Node* newNode=Node(data); head=head->next;
if(head==NULL){ }
return newNode; }
} Advantage & disadvantage of singly linked list
newNode->next=head;
return newNode;  Advantages:
}  very easier for the accessibility of a node in the forward
 Insert At End : direc on.
struct Node * addAtEnd(int data, struct Node* head){  the inser on and dele on of a node are very easy.
struct Node* newNode=Node(data);  require less memory when compared to doubly, circular
if(head==NULL){ linked list.
return newNode;  very easy data structure
}  Inser on and dele on of elements don’t need the
struct Node* temp=head; movement of all the elements when compared to an
while ( temp->next !=NULL)
array.
{
temp=temp->next;
 Disadvantages :
}  Accessing the preceding node of a current node is not
temp->next=newNode; possible as there is no backward traversal.
return head;  Accessing of a node is very me-consuming.
}
 Insert At specific Posi on : Doubly Linked List(DLL)

struct Node* addAtPos(int data , int pos , struct Node* head)  A DLL is a complex version of a SLL .
{  A DLL has each node pointed to next node as well as previous node.
if(pos==1){
return addAtBeg(data,head); }
struct Node* temp=head;
for (int i = 1; i <=pos; i++)
{ if(i!=pos && temp==NULL ){
return head; //invalid position
}
if(i==pos-1){  Representa on Node of DLL :
struct Node * newNode=Node(data);
newNode->next=temp->next; struct node
temp->next=newNode; {
return head; int data; //data item for storing value of the node
} struct node *next; //address of the next node
temp=temp->next; struct node *prev; //address of the previous node
}
};
return head;
}  create Node of DLL:
 Delete at beginning : struct Node* Node(int data){
struct Node* newNode=(struct Node*)malloc(sizeof(struct
struct Node * deleteAtBeg( struct Node* head){
Node ));
if(head==NULL){
newNode->prev= NULL;
return NULL;
newNode->data=data;
}
newNode->next=NULL;
return head->next;
return newNode;
}
}
 Delete at End :
Operations on DLL
struct Node * deleteAtEnd( struct Node* head){
if( head==NULL || head->next == NULL){  Insert At beginning :
return NULL;
} struct Node * addAtBeg(int data, struct Node* head){
struct Node* temp=head; struct Node* newNode=Node(data);
while (temp->next->next !=NULL){ if(head==NULL){
temp=temp->next; return newNode;
} }
temp->next=NULL; newNode->next=head;
return head; head->prev=newNode;
} return newNode;
}
 Insert At End : Circular Linked List (CLL)
struct Node * addAtEnd(int data, struct Node* head){  All nodes are connected to form a circle.
struct Node* newNode=Node(data);
 the first node and the last node are connected to each other
if(head==NULL){
return newNode; which forms a circle.
}  There is no NULL at the end.
struct Node* temp=head;
while ( temp->next !=NULL)
{
temp=temp->next;
}
temp->next=newNode;
newNode->prev=temp;
return head;
Operations on CLL
}
 Delete At beginning:  Insert at beginning
struct Node * deleteAtBeg( struct Node* head){  Insert at specific Posi on
if(head==NULL || head->next==NULL){  Insert at end
return NULL;  delete at beginning
}  delete at specific posi on
head ->next->prev = NULL;  delete at end
return head->next;
} Advantage & disadvantage of CLL
 delete At End :
 Advantages:
struct Node * deleteAtEnd( struct Node* head){  No need for a NULL pointer
if( head==NULL || head->next == NULL){  Efficient inser on and dele on
return NULL;
 Flexibility
}
struct Node* temp=head;  Disadvantages :
while (temp->next->next !=NULL){  Traversal can be more complex
temp=temp->next;  Reversing of circular list is a complex as SLL.
}
temp->next=NULL; Row major order & Column major order
return head;
} int arr[2][3]=
 Traverse DLL : { {1,2,3},
{4,5,6} } //2D array
void traverse(struct Node* head){
while (head!=NULL){ //row major order
printf("%d ", head->data); {1,2,3,4,5,6}
head=head->next; } } //column major order
 ReverseTraverse DLL: {1,4,2,5,3,6}
Address of any element in 1D array
void traverseRev(struct Node* head){
if(head==NULL) Address of A[I] = B + W * (I – LB)
return;
while (head->next!=NULL) I =element, B = Base address, LB = Lower Bound
head=head->next;
W = size of element in any array(in byte),
while (head!=NULL){
printf("%d ", head->data); Example: Given the base address of an array A[1300 ………… 1900] as
head=head->prev; 1020 and the size of each element is 2 bytes in the memory, find the
} address of A[1700].
}
Advantage & disadvantage of DLL Solution :

Address of A[I] = B + W * (I – LB)


 Advantages:
 It is bi-direc onal traversal Address of A[1700] = 1020 + 2 * (1700 – 1300)
 It is efficient dele on = 1020 + 2 * (400) = 1020 + 800=1820
 Inser on and dele on at both ends in constant me
 Disadvantages : Address of any element in 2D array
 Increased memory usage
Row major order : A[I][J] = B + W * ((I – LR) * N + (J – LC))
 More complex implementa on
 It is slower traversal I = Row element , j=column element , LR=lower limit of row

N = No. of column given in the matrix , LC=lower limit of column


Example: Given an array, arr[1………10][1………15] with base value
100 and the size of each element is 1 Byte in memory. Find the
address of arr[8][6] with the help of row-major order.
Formula:

Address of A[I][J] = B + W * ((I – LR) * N + (J – LC))


Solution:

N = Upper Bound column – Lower Bound column + 1

A[8][6] = 100 + 1 * ((8 – 1) * 15 + (6 – 1)) = 100 + 1 * ((7) * 15 + (5))

= 100 + 1 * (110)=210

column major order :


A[I][J] = B + W * ((J– LC) * M + (I – LR))

N = No. of rows given in the matrix

Example: Given an array, arr[1………10][1………15] with base


value 100 and the size of each element is 1 Byte in memory. Find
the address of arr[8][6] with the help of row-major order.
Formula:

A[I][J] = B + W * ((J– LC) * M + (I – LR))

Solution:

M = Upper Bound row – Lower Bound row + 1

A[I][J] = B + W * ((J – LC) * M + (I – LR))

A[8][6] = 100 + 1 * ((6 – 1) * 10 + (8 – 1))

= 100 + 1 * ((5) * 10 + (7))= 100 + 1 * (57)= 157

Difference between Array and Linked List

Array Linked List


It is stored in a contiguous It can be stored randomly in
memory location. the memory .
elements are independent of elements are dependent on
each other. each other
memory is allocated at memory is allocated at run
compile-time. time
Accessing any element in an Accessing an element in a
array is faster linked list is slower
Array takes more time while Linked list takes less time while
performing any operation like performing any operation like
insertion, deletion, etc. insertion, deletion, etc.
Stack Implementation of stack using Linked List

 It is a linear data structure that follows a particular order in #include<stdio.h>


which the operations are performed. #include<stdlib.h>
struct Stack
 The order may be LIFO(Last In First Out) or FILO(First In Last
{
Out). int data;
 The inser on and dele on opera on in stack are known struct Stack* next;
as PUSH and POP opera ons. };
 Push and pop done at the top of the stack . struct Stack* Node(int data){
 opera on can be performed on stack : struct Stack * newNode=(struct Stack* ) malloc(sizeof(struct Stack));
newNode->data=data;
 push () : insert item in stack newNode->next=NULL;
 pop() : delete top item in stack return newNode;
 peek() : access the top item of stack }
 All opera on done in constant me O(1) me complexity struct Stack* push(struct Stack * top , int data){
struct Stack* newNode=Node(data);
if(top!=NULL){
newNode->next=top;
}
return newNode;
}
int peek(struct Stack * top){
return top->data;
Implementation of stack using array }
struct Stack * pop(struct Stack * top ){
#include <stdio.h> return top->next;
#define MAX 100 }
int stack[MAX],top = -1; void main(){
void push(int val) struct Stack * top=NULL;
{ top=push(top,5);
if (top == MAX) top=push(top,15);
printf("\n Overflow"); int val=peek(top); // 15
return; top=pop(top);
top = top + 1; int val=peek(top); // 5
stack[top] = val; top=push(top,3);
} val=peek(3); // 3
int peek(){ }
return stack[top];
Algorithm of push or pop operation
}
void pop()
PUSH(stack, data): //algo of push() operation
{
if (top == -1) 1. top ==Max-1 then print "stack overflow " stop
printf("Underflow"); 2. top increment by 1
else 3. stack[top]=data
top = top - 1; 4. stop
}
void show()
POP(stack): //algo of pop() operation
{
for (int i = top; i >= 0; i--) 1. top<0 then print "stack underflow " stop
printf("%d\n", stack[i]); 2. top decrement by 1
if (top == -1) 3. stop
printf("Stack is empty"); Application of Stack
}
void main()  Back and forward buttons in a web browser:
{  Undo/redo functionality in text editors a
push(4); // insert the item  Expression conversion (postfix , infix )
push(2); // insert the item  Parenthesis checking
show(); // show the items
 String reversal
pop(); // insert the item
show(); //show the items of the stack  Infix and postfix notation
int val =peek(); // get the top value
printf("top element %d " ,val); // print value (a+b) * c -- infix nota on
ab+c* -- pos ix nota on
}
 Conversion of Infix to postfix using stack Recursion
Infix nota on : A + (B*C – (D/E ^ F)*H)
 Recursion is the technique of making a func on call itself.
Expression stack postfix  This provides to break problems into sum problems which
A A are easier to solve.
+ + A  Recursion may be a bit difficult to understand.
( +( A  A simple base case (or cases) — it tells the function when to
B +( AB stop. if we fail to include this condition it will result in
* +(* AB infinite recursions.
C +(* ABC  A recursive step — a set of rules that reduces problems to
subproblems.
- +(- ABC*
 Example:
( +(-( ABC*
int recursion(int n){
D +(-( ABC*D
if(n==0) return 1; //base case
/ +(-(/ ABC*D
return n*recursion(n-1); //recursive step
E +(-(/ ABC*DE
}
^ +(-(/^ ABC*DE
Types of Recursion
F +(-(/^ ABC*DEF
) +(- ABC*DEF^/  Direct recursion: A func on is directly recursive if it contains
* +(-* ABC*DEF^/ an explicit call to itself.
H +(-* ABC*DEF^/H  Indirect recursion: A func on is indirectly recursive if it
) + ABC*DEF^/H*- contains a call to another func on
ABC*DEF^/H*-+  Tail recursion: is defined as a recursive func on in which the
 Infix to postfix using arithmetic expression recursive call is the last statement that is executed by the
Infix nota on : A + (B * C + D)/E. func on.
 Tree recursion : In which we call multiple recursive call like
A + (B * C + D)/E T1=BC* fibo(n) =fibo(n-1) + fibo(n-2)
A + (T1+ D)/E T2=T1D+  Example of type of recursion
A+T2/E T3=T2E/ int foo(int n){ int foo (int x) int recursion(int n){
A+T3 T4=AT3+ if(n==0) { if(n==0) return 1;
return 1; if (x <= 0) return n*recursion(n-1);
T4 PUT T4 return foo(n-1); return x; }
AT3+ PUT T3 } return bar (x) ;
AT2E/+ PUT T2 }
int bar (int y)
AT1D+E/+ PUT T1 { return foo (y – 1) ; }
ABC*D+E/+ direct recursion indirect recursion tail recursion
postfix to infix Notation Tower of Hnoi

 pos ix nota on : 752+*

7 7
5 7,5
2 7,5,2
+ 7,(5+2)
* 7*(5+2)
 Tower of Hanoi is a mathematical puzzle where we have
three rods (A, B, and C) and N disks. Initially, all the disks
Iteration are stacked in decreasing value of diameter
 Itera on is when same procedure is repeated mul ple mes  Only one disk can be moved at a time.
 Each repe on of process is a single itera on  Each move consists of taking the upper disk from one of
 Result of each itera on is star ng point of next itera on. the stacks
 No disk may be placed on top of a smaller disk.
 Itera on allows us to simplify our algorithm .
 Total no. of steps to solve of n disk = 2n – 1 = 2*3 – 1 = 7
 Itera on done by using loop of the languages
 Example : factorial , fibonocci , sum of array etc Algorithm of Tower of Hnoi
int arr[5]={1,2,3,3,4} , sum =0 ; void TOH(n , s , a , d):
for (int i = 0; i < 5; i++) 1. if n==0
{ 2. return
sum+=arr[i]; 3. TOH(n-1,s,d,a) //recursive call
} 4. print(s+"to"+d)
printf("%d",sum); 5. TOH(n-1,a,s,d) // recursive call
Tower of Hnoi program in C void show()
{
#include<stdio.h> if (Front == - 1){
void towers( int num, char S, char A, char D) printf("Empty Queue \n");
{ return ;
if (num == 0) }
return; for (int i = Front; i <= Rear; i++){
towers (num - 1, S,D , A); printf("%d ", queue[i]);
printf ("\n Move disk %d from peg %c to peg %c", num, S, D); }
towers (num - 1, A, S, D); }
} int main()
int main() {
{ show(); // show the items of the queue
int num; insert(4); // insert the item on the top of queue
printf ("Enter the number of disks : "); insert(2); // insert the item on the top of queue
scanf ("%d", &num); show(); // show the items of the queue
printf ("The sequence of moves :\n"); delete(); // insert the item on the top of queue
towers (num, 'A', 'B', 'C'); show(); //show the items of the queue
return 0; }
} Implementation of queue using Linked List
Queue
#include<stdio.h>
 A Queue is defined as a linear data structure #include <stdlib.h>
struct Queue {
 Queue uses two pointers − front and rear.
int data;
 Dele on done using front pointer.inser on done using rear struct Queue* next;
pointer. };
 Queue follows the First In First Out (FIFO) rule . struct Queue* front = NULL;
 all opera on of done at constant O(1) me struct Queue* rear = NULL;

 opera on can be performed on queue : void insert(int data) {


 insert () : insert item in queue struct Queue* newQueue = (struct Queue*)malloc(sizeof(struct Queue));
newQueue->data = data;
 delete () : delete top item in queue
newQueue->next = NULL;
if (front == NULL && rear == NULL) {
front = rear = newQueue;
return;
}
rear->next = newQueue;
rear = newQueue;
}
Implementation of queue using array
int delete() {
#include <stdio.h>
if (front == NULL) {
#include<stdlib.h>
printf("Queue is empty");
# define SIZE 100
return -1;
int queue[SIZE];
}
int Rear = - 1,Front=-1;
int data = front->data;
void insert(int data)
if (front == rear)
{
front = rear = NULL;
if (Rear == SIZE - 1){
else
printf("Overflow \n");
front = front->next;
return ;
}
return data;
if (Front == - 1){
}
Front = 0;
}
void main() {
queue[++Rear] = data;
insert(10);
}
insert(20);
void delete ()
printf("%d ", delete());
{
printf("%d ", delete());
if(Front==Rear){
printf("%d ", delete());
Front=Rear=-1;
}
}
if (Front == - 1 ) Algorithm of insert & delete operation in queue
{
printf("Underflow \n"); function insert(data , queue,rear ,front ,size ):
return ; 1. if rear==size -1 then print "queue overflow" stop
} 2. else
Front = Front + 1; 3. check if front ==-1 then set front =0
} 4. set rear=rear+1 and queue[rear]=data
5. endif
function delete ( queue,rear ,front ): {
1.if rear=front then set front=rear=1 endif printf("%d ", cqueue[i]);
2. if front==-1 then print "queue underflow " stop endif i++; }
}
3.set front =front +1
else{
Application of Queue while (i<=SIZE-1)
{
 Add a song into playlist printf("%d ", cqueue[i]);
 Printers i++;
 Used in graph traversal bfs algorithm }
i=0;
 Ticket windows while (i<=rear)
 Bus stop {
printf("%d ", cqueue[i]);
Circular queue i++;
}
 A Circular Queue is an extended version of a normal queue } } }
 Last element is connected to the first element of the queue int main(int argc, char const *argv[])
forming a circle. {
insert(5);
 new element is done at the very first loca on of the queue if insert(6);
the last loca on at the queue is full. display();
delete();
display();
return 0;
}
Dequeue

 Inser on and dele on opera ons are performed at both


ends .
 This dequeue can be used both as a stack and as a queue

Implementation of circular queue using array


Types of Dequeue
#include<stdio.h>
#define SIZE 5
 input restricted queue, inser on opera on can be
int cqueue[SIZE],front=-1,rear=-1;
void insert(int value ){ performed at only one end, while dele on can be
if((front==0 && rear ==SIZE-1) || (front==rear+1)){ performed from both ends.
printf("queue is full ");  output restricted queue, dele on opera on can be
} performed at only one end, while inser on can be
else{
if(rear==SIZE-1 && front!=0){
performed from both ends
rear=-1;
Input restricted dequeue
}
cqueue[++rear]=value;
if(front==-1){
front=0;
} output restricted dequeue
} }
void delete(){
if(front==-1 && rear==-1){
printf("queue is empty ");
}
else{ Priority Queue
front=front+1;
if(front==SIZE){  It is data structure that behaves like a normal queue
front=0; except that each element has some priority,
}
if(front-1==rear){  elements are either arranged in an ascending or
front=rear=-1; descending order.
}  It has 2 type:
} }
void display(){  1. Ascending PQueue 2. Descending PQueue
if(front==-1){
printf("queue is empty"); Application priority Queue
}
else{  Optimization problems
int i =front;  Heap sort using priority queue
if(front<=rear){  Dijkstra shortest path find using priority queue
while (i<=rear)  Scheduling the jobs in OS
Searching Algorithm of Binary Search

 Searching Algorithms are designed to check for an element BS(arr, l,r,ele)


or retrieve an element from any data structure where it is 1. if l>r then return -1 stop
stored. 2. mid=l+(r-l)/2
 There are two searching techniques : 3. if arr[mid]==ele then return mid stop
 a. Linear search (sequen al) b. Binary search 4. if arr[mid ] < ele then return BS(arr,mid+1,r,ele) //for left array
5. if arr[mid ] > ele then return BS(arr,l,mid-1,ele) //for right array
Linear Search
Explana on:
 It is the simplest searching algorithm  If ele== mid, then return mid.Else, compare the element to
 Each element read one by one sequen ally and compared be searched with m.
with the desired elements is known as linear search .  If ele > mid, compare x with the middle element of the
 It is widely used to search an element from the unordered list elements on the right side of mid. This is done by
 Worst-case me complexity of linear search is O(n) setting l to l = mid + 1.
 The space complexity of linear search is O(1).  Else, compare ele with the middle element of the elements
on the left side of mid. This is done by setting r to r = mid-1
Hashing

 It is a process of mapping keys, and values into the hash table


by using a hash func on.
 It is done for faster access to elements.
 we transform large key to small key using hash func on
 In Hashing, Using the hash func on, we can calculate the
Algorithm of Linear Search address at which the value can be stored.
Linear_search(Array, ele, n)
 Each element is assigned a key. By using that key we can
1. for i = 0 to n-1 then check access the element in O(1) me.
2. if (Array[i] = ele ) then return i  In a hash table , we have number of fixed slots to store the
3. enfor value .
4. return -1  Hash Key = Key Value % Number of Slots in the Table
Explana on:  Examples of Hashing in Data Structure:

 First, we have to traverse the array elements using a for loop.  In schools, roll number to retrieve information about
 In each itera on, compare the search element with the that student.
current array element, and -  A library has an infinite number of books. The librarian
 If the element matches, then return the index of the assigns a unique number to each book. This unique
corresponding array element. number helps in identifying the position of the books on
 If the element does not match, then move to the next the bookshelf.
element.
 If there is no match or the search element is not present in Hash function and their types
the given array, return -1.
 The hash function is used to arbitrary size of data to fixed-
Binary Search sized data.
 It is search technique that works efficiently on sorted lists.  hash = hashfunction(key)
 we must ensure that the list is sorted.
 Binary search follows the divide and conquer approach a. Division method :
 Array divided into two parts and compared with middle
 The hash func on H is defined by :
index of the element of the array
 If the middle elements matched with the desired element  H(k) = k (mod m) or H(k) = k (mod m) + 1
then we return the index of the element  Here k (mod m) denotes the remainder when k is divided
 Time complexity of the algo is O(logn) by m.
 Example: k=53 , m=10 then h(53)=53mod10 =3

b. Midsquare method :

 The hash func on H is : H(k) = h(k*k)=l


 l is obtained by dele ng digits from both end of k2.
 Example : k=60
 therefore k=3600
 then remove digits from both end we get h(k) =60
c. Folding method :  Op onally, maintain the linked list in sorted order, with each
element containing the whole record including the key.
 The key k is par oned into a number of parts, k1, ... ,kr,
 To insert, find the hash value with a hash func on, and insert
 Then the parts are added together H(k) = k1 + k2 + ....+ kr
the element into the linked list.
 Now truncate the address upto the digit based on the
size of hash table.  For searching, find the hash key in the hash table, then
search the element in the corresponding linked list.
 Example : k = 12345
k1 = 12, k2 = 34, k3 = 5  Dele on involves a search opera on and then dele ng the
s = k1 + k2 + k3= 12 + 34 + 5= 51 element from the linked list.

Hash Collision Garbge collection

 hash collision or hash clash is when two pieces of data in a  Garbage collec on in hashing reclaims memory/resources
hash table share the same hash value from deleted elements that are no longer in use
 It enhances hash table efficiency. Typically automa c, it's
Collision resolution technique managed by the data structure or language run me.
 Mechanisms vary by language/implementa on.
 We have two method to resolve this collision in our hashing .
these are following below : Insertion sort
 1. Open addressing 2.seperate chaining
 This is an in-place comparison-based sor ng algorithm.
1.Open addressing  Here, a sub-list is maintained which is always sorted.
 The array is searched sequen ally and unsorted items are
 Open addressing stores all elements in the hash table itself. moved and inserted into the sorted sub-list (in the same
 It systema cally checks table slots when searching for an array).
element.  average and worst case complexity are of Ο(n2)
 In open addressing, the load factor (λ) cannot exceed 1.
 Load Factor (λ) = Number of Elements Stored / Total Number
of Slots
 Probing is the process of examining hash table loca ons.
 Linear Probing
 it systema cally checks the next slot in a linear manner
un l an empty slot is found.
 This process con nues un l the desired element is
located
 method of linear probing uses the hash func on
h(k,i)= (k %m + i) mod m , where m is size of table
 Quadra c Probing
 it checks slots in a quadra c sequence (e.g., slot + 1, slot
+ 4, slot + 9, and so on) un l an empty slot is found.
 This con nues un l the desired element is located or the
table is en rely probed.
 method of Quadra c probing uses the hash func on Algorithm of Insertion sort
h(k,i)= (k %m + i^2) mod m
 Double Probing 1. for j =2 to length[A]
 it uses a second hash func on to calculate step size for 2. set key = A[j] and i=j-1
probing, providing a different sequence of slots to check. 3. while i > 0 and A[i] > key then
 This con nues un l an empty slot is found or the desired 4. A[i + 1] = A[i]
element is located. 5. i=i–1
 method of Quadra c probing uses the hash func on 6. endwhile
H1(k) = k%N and H2(k) = P - (k%P) 7. A[i + 1] = key
H(k, i) = (H1(k) + i*H2(k))%N 8. endfor
Where p is the prime Number less than k Bubble sort

 Bubble sort is the simplest sor ng algorithm that works by


2. Seperate chaining
repeatedly
 Maintain chains of elements with the same hash address.  swapping the adjacent element if they are in wrong order.
 Use an array of pointers as the hash table.  It is very efficient in large sor ng jobs. For n data items, this
 Size of the hash table can be the number of records. method requires n(n – 1)/2 comparisons.
 Each pointer points to a linked list where elements with the  Worst-case me complexity of algo is O(n^2).
same hash address are stored.
Similarly repeat step un l we get sorted array

 It is based on the Divide and Conquer algorithm


 Picks an element as a pivot and par ons the given array
 Placing the pivot in its correct posi on in the sorted array.
Algorithm of Bubble sort
 Then these two sub-arrays are sorted separately.
bubblesort(Arr, n ):
Algorithm of quick sort
1. for i=1 to n-1:
2. for j=1 to n-i : 1. partition(arr,l,r):
3. if arr[j]>arr[j+1] then swap(arr[j],arr[j+1]) 2. pivot=arr[r]
4. endfor 3. for j=l upto r :
5. endfor 4. check arr[j] < pivot then
Selection sort 5. do swap(arr[l],arr[j]) and l++
6. endfor
 In this sor ng , we find the smallest element in the given and
7. swap(arr[l],arr[r])
moves it final posi on of the array .
8. return l
 We then reduce the effec ve size of the array by one
element and repeat the process on the smaller sub-array.
 The process stops when the effec ve size of the array 1. QUICKSORT (array A, l, r):
2. if (l < r) :
becomes 1
3. p = partition(A, l, r)
 Worst Time complexity of algorithm is O(n^2). 4. QUICKSORT (A, l, p - 1)
5. QUICKSORT (A, p + 1, r)
6. endif
complexity of quick sort :

 Best TC: O(nlogn) SC: O(1)


 Average TC : O(nlogn)
 Worst TC: O(n^2)

Merge sort

Algorithm of Selection sort  Merge sort is a sor ng algorithm that uses the idea of divide
and conquer.
1. Selection-Sort (A,n) :  This algorithm divides the array into two subarray , sorts
2. for j = 1 to n – 1: them separately and then merges them.
3. sm = j
4. for i = j + 1 to n:
5. if A [i] < A[sm] then sm = i
6. Swap (A[j], A[sm])
Quick sort

complexity of merge sort :

 Best TC: O(nlogn) SC: O(n)


 Average TC : O(nlogn)
 Worst TC: O(nlogn)
Algorithm of merge sort  It finds largest element and puts it at the end of array, then
 second largest item is found and this process is repeated for
1. mergesort(arr, l, r) all other elements. Heapsort is non-stable sor ng
2. if l < r
3. set mid = l+(r-l)/2
 The general approach of heap sort is as follows :
4. mergesort(arr, l, mid)  From the given array, build the ini al max heap.
5. mergesort(arr, mid + 1, r)  Interchange the root (maximum) element with the last
6. MERGE (arr, l, mid, r) element.
7. endif
 Use repe ve downward opera on from root node to
8. END mergesort
rebuild the
 heap of size one less than the star ng.
1. void merge(int a[], int l, int m, int r):  Repeat step (a) and (b) un l there are no more elements.
2. set n1 = m - l + 1, n2 = r - m
3. initialize Left[n1], Right[n2]; Algorithm of Heapsort sort

4. // copy the left data in left array BuildHeap(arr)


5. for i=0 upto n1 : 1. for i = length(arr)/2-1 to 0
6. Left[i] = a[l + i] 2. Heapify(arr,i)
7. // copy the right data in right array
8. for j=0 upto n2 : Heapify(A,i,n):
9. Right[j] = a[m + 1 + j] 1. Initializes l=2*i+1 , r=2*i+2, largest =i
2. if l < n and A[l] > A[i] then largest=l
10. set i = 0, j = 0 ,k = l
3. if r <n and A[r] > A [largest] then largest = r
11. while (i < n1 && j < n2) :
4. if largest != i :
12. if(Left[i] <= Right[j]) :
5. swap(A[i],A[largest])
13. a[k] = Left[i++]
6. Heapify(A,largest)
14. else :
15. a[k] = Right[j++]
16. k++; HeapSort(A) :
1. BuildHeap(A)
17. while (i<n1) : 2. for j = length [A] down to 1
18. a[k++] = Left[i++]; 3. swap(A[1] , A[j])
19. while (j<n2) : 4. Heapify (A, 0,j)
20. a[k++] = Right[j++]; complexity of Heap sort :

Heap sort  Best TC: O(nlogn) SC: O(1)


 Average TC : O(nlogn) Worst TC: O(nlogn)
Radix sort

 Radix sort is the linear sor ng algorithm that is used for


integers. It is stable sor ng .
 In which,according to digit sor ng is performed that is
started from the right to le digit.
 Example : we have 7 elements in array to sort the array using
radix technique.
Arr=[329,457, 657, 839, 436, 720, 355]

Algorithm of Radix sort

radixSort(arr)
1. max = largest element in arr
2. d = number of digits in max
3. Now, create d buckets of size 0 - 9
4. for i -> 0 to d
5. sort the arr elements using counting sort
complexity of Radix sort :

 Best TC: O(n+k) SC: O(n)


 Average TC : O(nk) Worst TC: O(nk
Graph  Graphs are used to represent networks of communica on.
 Graphs are used to represent data organiza on.
 A graph is a non-linear data structure consis ng of nodes
 Graphs are used for topological sor ng etc.
and edges .It has finite set of ver ces (or nodes) and set of
edges. Terminologies of graph
 Graph denoted as G(E,V) , where E=edge , V=ver ces

Types of Graph Term Description


 Undirected Graph Vertex individual data element is called vertex(node)
 when all the edges present between any ver ces of
the graph are un-directed or have not defined
Edge It is connec ng link between two nodes
direc on.
 Directed Graph Undirected edge It is a bidirec onal edge.
 when all the edges present between any ver ces of
the graph are directed or have a defined direc on. Directed Edge It is a unidirec onal edge.
 Weighted Graph
 each edge of a graph has an associated numerical Weighted Edge An edge with value (cost) on it.
value, called a weight. Usually ,the edge weights are
non- nega ve integers.
Degree total number of edges connected to a
vertex .

Indegree number of incoming edges connected to vertex.

Outdegree total number of outgoing edges connected to


vertex.
 Connected Graph
 A connected graph is a graph in which there is a path Self-loop an edge that connects a vertex to itself.
between every pair of ver ces.
 Simple Graph Adjacency Ver ces are said to be adjacent if edge is
connected.
 A graph or directed graph which does not have any
selfloop or parallel edges is called a simple graph Representations of graph
 Mul -graph
 Here are the two most common ways to represent a
 A graph which has either a self-loop or parallel edges
graph :
or both is called a mul -graph
1. Adjacency Matrix 2.Adjacency List

1.Adjacency Matrix
 An adjacency matrix is a way of represen ng a graph as a
matrix of boolean (0’s and 1’s).
 Let’s assume there are n ver ces in the graph So, create a
 Acyclic graph 2D matrix adjMat[n][n] having dimension n x n.
 If a graph (digraph) does not have any cycle then it is  If there is an edge from vertex i to j, mark adjMat[i][j] as 1.
called as acyclic graph.  If there is no edge from vertex i to j, mark adjMat[i][j] as 0.
 Cyclic graph
 A graph that has cycles is called a cyclic graph.
 Regular graph
 all graph ver ces should have the same degree.

Applications Graph
Graph theory is used to find shortest path in road or a
network.
2. Adjacency List Implement DFS algorithm (Numerical)
 An array is used to store edges between two ver ces
 The size of array is equal to number of ver ces.
 Each index in array represents a specific vertex in the
graph.
 The entry at the index i of the array contains a linked list
containing the ver ces that are adjacent to vertex i.

Adjacency list of the given graph :

 1  2, 7
 23
 3  5, 4, 1
 46
 54
 6  2, 5, 1
 7  3, 6
1. Ini ally set unvisited for all vertex
2. Push 1 onto stack
3. Stack =1
4. Pop 1 from stack , set vis[1]=1 and Push 2, 7 onto stack
DFS = 1 stack = 2 7
5. Pop 7 from stack , set vis[7]=1 Push 3, 6;
DFS = 1, 7 stack =2 3 6 .
6. Pop 6 from stack , set vis[6]=1 Push 5;
DFS = 1, 7, 6 stack =2 3 5 .
Graph traversal
7. Pop 5 from stack , set vis[5]=1 Push 4;
 Graph is represented by its nodes and edges, so traversal
DFS = 1, 7, 6, 5 stack = 2 3 4
of each node is the traversing in graph.
8. Pop 4 from stack, set vis[4]=1
 There are two standard ways of traversing a graph
DFS = 1, 7, 6, 5, 4 stack= 2,3
1.Depth first search 2. Breadth first search
9. Pop 3 from stack , set vis[3]=1
1.Depth-first-search [DFS] DFS = 1, 7, 6, 5, 4, 3 stack =2
10. Pop 2 from stack, set vis[2]=1
 Dfs is the searching or traversing algorithm , in which we DFS = 1, 7, 6, 5, 4, 3,2
used the stack data structure . 11. Now, the stack is empty, so the depth first traversal of a
 In dfs ,we will first focus on the depth then go to the given graph is 1, 7, 6, 5, 4, 3 2.
breadth at that level.
 Time complexity : O( V + E) & space complexity :O(v) 2.Breadth-first-search [BFS]
Algorithm:  Bfs is the searching or traversing algorithm , in which we
used the queue data structure .
Step 1: SET STATUS = 1 (ready state) for each node in G
 In bfs ,we will first focus on the breadth then go to the
Step 2: Push the star ng node A on the stack and set its
depth at that level.
STATUS = 2 (wai ng state)
 Time complexity : O( V + E ) & space complexity :O(v)
Step 3: Repeat Steps 4 and 5 un l STACK is empty Algorithm:

Step 4: Pop the top node N. Process it and set its STATUS = 3 Step 1: SET STATUS = 1 (ready state) for each node in G
(processed state) Step 2: Enqueue the star ng node A into the queue and set its
STATUS = 2 (wai ng state)
Step 5: Push on the stack all the neighbors of N that are in the
ready state (whose STATUS = 1) and set their STATUS = 2 Step 3: Repeat Steps 4 and 5 un l queue is empty
(wai ng state)
Step 4: dequeue node N. Process it and set its STATUS = 3
(processed state)
Step 5: Push on the queue all the neighbors of N that are in the Connected component
ready state (whose STATUS = 1) and set their STATUS = 2  A connected component in a graph is a subgraph in which
(wai ng state) there is a path between every pair of ver ces. In other
Implement BFS algorithm (Numerical) words, all ver ces in a connected component are mutually
reachable.

Strongly Connected component


 A directed graph is strongly connected if there is a path
between all pairs of ver ces.
 Kosaraju’s algorithm is used to find strongly connected
components in a graph.
 In this graph we have 3 strongly connected component
 1. A B C 2. D 3. E F G

Adjacency list of the given graph :

 A  F, C, B
 B  G, C
 C F
 D C
 E  D, C, J
 F D
 G  C, E Spanning Tree
 J  D, K  A spanning tree of an undirected graph is a sub-graph that
 K  E, G is a tree which contains all the ver ces of graph.
 A spanning tree of a connected graph G contains all the
 Ini ally set unvisited for all vertex
ver ces and has the edges which connect all the ver ces.
 Push A into queue So, the number of edges will be 1 less than the number of
Queue =A nodes.
 Delete A from queue, set vis[A]=1 , insert F,C,B into queue  A connected graph may have more than one spanning
BFS = A queue = F,C,B trees.
 Delete F from queue, set vis[F]=1 and insert D into queue
BFS = A,F queue = C,B,D
 Delete C from queue, set vis[C]=1
BFS = A,F ,C queue = B,D
 Delete B from queue, set vis[B]=1 and insert G into queue
BFS = A,F ,C,B queue = D,G
Minimum Spanning Tree [MST]
 Delete D from queue, set vis[D]=1
 In weighted graphs, a minimum spanning tree is spanning
BFS = A,F ,C,B,D queue = G
tree with the minimum possible sum of edge weights.
 Delete G from queue, set vis[G]=1 and insert E into queue
BFS = A,F ,C,B,D,G queue = E
 Delete E from queue, set vis[E]=1 and insert J into queue
BFS = A,F ,C,B,D,G,E queue = J
 Delete J from queue, set vis[J]=1 and insert K into queue
BFS = A,F ,C,B,D,G,E,J queue = K
 Delete K from queue, set vis[K]=1
BFS = A,F ,C,B,D,G,E,J,K
 Now, the queue is empty, so the breadth first traversal of a
given graph is A,F ,C,B,D,G,E,J,K
Prim’s algorithm Algorithm :
 It is a greedy algorithm that is used to find the minimum
spanning tree from a graph. 1. Create a forest where each vertex is a separate tree.
 Prim's algorithm starts with the single node and explores 2. Sort all the edges in non-decreasing order of their weights.
all the adjacent nodes with all the connec ng edges at 3. Pick the smallest edge. Check if it does not form a cycle then
every step. It is used for undirected graph . include int the spanning tree .
 me complexity :O(E Log V)) & space complexity : O(V) 4. Repeat step 3 un l there are (V-1) edges in the minimum
spanning tree, where V is the number of ver ces.
Algorithm:
Implement kruskal’s algorithm (Numerical)
Step1. Choose a star ng vertex.
Step2. Repeat un l there are fringe ver ces:
a. Select the minimum-weight edge (e) connec ng the tree
and fringe vertex[not included].
b. Add the chosen edge and vertex to the minimum
spanning tree (T).
Step3. Exit.

Implement Prim’s algorithm (Numerical)

Dijkstra algorithm
 Dijkstra's algorithm is an algorithm for finding the shortest
paths between nodes in a weighted graph,
 It is a type of Greedy Algorithm that only works on
Weighted Graphs having posi ve weights.
 It can also be used for finding the shortest paths from a
single node to a single des na on
 me complexity : O( E log V) & space complexity : O( V)

Algorithm :
Step 1: First, we will mark the source node with a current
distance of 0 and set the rest of the nodes to INFINITY.

Step 2: We will then set the unvisited node with the smallest
current distance as the current node “curr”.
Kruskal's Algorithm
 It is a greedy algorithm that is used to find the minimum Step 3: For each neighbor N of the current node “curr”:
spanning tree from a graph. If dist[curr]+weight[N] < dist[N] then Set dist[N] =
 In Kruskal's algorithm, we start from edges with the lowest dist[curr]+weight[N]
weight and keep adding the edges un l the goal is
reached. Step 4: We will then mark the current node “curr” as visited.
 me complexity :O(E Log E)) & space complexity : O(V)
Step 5: We will repeat the process from 'Step 2' if there is any
node unvisited le in the graph.
Implement dijkstra algorithm (Numerical) Implement Floyd warshall algorithm (Numerical)

matrix A0
0 1 2 3 4

0 0 3 8 ∞ -4

1 ∞ 0 ∞ 1 7

2 ∞ 4 0 ∞ ∞

3 2 ∞ -5 0 ∞

4 ∞ ∞ ∞ 6 0

matrix A1 matrix A2
0 1 2 3 4 0 1 2 3 4

0 0 3 8 ∞ -4 0 0 3 8 4 -4

1 ∞ 0 ∞ 1 7 1 ∞ 0 ∞ 1 7

2 ∞ 4 0 ∞ ∞ 2 ∞ 4 0 5 11
3 2 5 -5 0 -2 3 2 5 -5 0 -2
4 ∞ ∞ ∞ 6 0 4 ∞ ∞ ∞ 6 0

matrix A3 matrix A4

0 1 2 3 4 0 1 2 3 4

0 0 3 8 4 -4 0 0 3 -1 4 -4

1 ∞ 0 ∞ 1 7 1 3 0 -4 1 -1
2 ∞ 4 0 5 11 2 7 4 0 5 3
Floyd warshall algorithm 3 2 -1 -5 0 -2 3 2 -1 -5 0 -2
 It is a dynamic programming algorithm used to discover 4 ∞ ∞ ∞ 6 0 4 8 5 1 6 0
 the shortest paths in a weighted graph
 In which includes both posi ve & nega ve weight cycles.
 It is also called all pair shortest path algorithm Final matrix
 Time complexity : O(N^3) & space complexity: O(V^2)
0 1 2 3 4

Algorithm 0 0 1 -3 2 -4
1. Create a matrix 'dist' of size VxV (V is number of ver ces)
and ini alize it with the weights of the edges in the graph. 1 3 0 -4 1 -1
- If there is no direct edge between ver ces i and j, set 2 7 4 0 5 11
dist[i][j] to infinity.
- If there is a direct edge between ver ces i and j with weight 3 2 -1 -5 0 -2
w, set dist[i][j] to w. 4 8 5 1 6 0
2. For each vertex 'k' from 1 to V:
a. For each pair of ver ces 'i' and 'j':
i. If dist[i][k] + dist[k][j] is less than dist[i][j],
update dist[i][j] to dist[i][k] + dist[k][j]
3. The final 'dist' matrix contains the shortest path distances
between all pairs of ver ces.
Tree Binary tree:
 A tree is a nonlinear hierarchical data structure .  When any tree has at most two child , those tree is said
 It consists of nodes connected by edges. to be binary tree.
 In which , easy to navigate and search.

Strictly binary tree


 A strictly binary tree is a binary tree in which each node
has either 0 or 2 children, i.e., no node has only one child.

Terminologies of Tree
 Node
 A node is an entity that contains a key or value and
pointers to its child nodes.
 Edge
 It is the link between any two nodes.
 Root Complete binary tree
 It is the topmost node of a tree. [10]  All levels are filled, except possibly the last.
 Child node:  Nodes are filled from left to right on all levels.
 Any subnode of a given node is called a child node.
 Ex: 20 & 30 & 50 are children of 10 etc.
 Parent:
 If node contains any sub-node, then node is called
parent of that sub-node.
 Ex: 30 is parent of 60 and 40 is parent of 70 etc.
 Sibling:
 The nodes that have the same parent are known as
siblings.
 Leaf Node:-
 The node of the tree, which doesn't have any child
node Extended binary tree
 Leaf nodes can also be called external nodes.  A binary tree T is said to be 2-tree or extended binary
 Ex : 70 ,80, 90 , 25,20, 50 tree if each node
 Internal nodes:  has either 0 or 2 children.
 A node has atleast one child node .  b. Nodes with 2 children are called internal nodes and
 Ex: 10 , 30 , 40 , 60 nodes with 0 children
 are called external nodes.
 Height of a Node
 The height of a node is the number of edges from
the node to the deepest leaf
 Ex:height(30) =2 &height(20) = 0 &height(10) =3
 Depth of a Node
 The depth of a node is the number of edges from
the root to the node.
 Ex : depth(30) =1 & depth(80) = 3 depth(10) =0
 Height of a Tree Binary tree
 The height of a Tree is the height of the root node . extended binary tree
 Ex: Height(root=10) = 3
Representation of Binary Tree using  Tree traversal is the process of visiting and processing
each node in a tree data structure.
linked list  The three main types of tree traversal are:
 Node structure :  In-order: 2 7 5 6 11 1 5 9 9
Each node in tree is represented by an object .  Pre-order: 1 7 2 6 5 11 9 9 5
 Post-order: 2 5 11 6 7 5 9 9 1

 In-order traversal: ( L N R)
Algorithm :
1. Traverse the left sub-tree.
2. Visit the root node.
 Data : the value stored in node . 3. Traverse the right sub-tree.
 Left child: pointer of left subtree of that node
 Right child : pointer of right subtree of that node Pseudo-code :
1.void in-order(struct node *root)
2. {
3. if(root!= NULL)
4. {
5. in-order(root→ left);
6. printf("%d",root→ data);
7. in-order(tree→ right);
8. }
9. }
 Pre-order traversal: (N L R)
Algorithm :
Representation of Binary Tree using 1.Visit the root node.
2.Traverse the left subtree.
array 3.Traverse the right subtree.
 Root Node : index 0 of the array
 Parent-child relationship : for any element at index I, its Pseudo-code :
left child is at index 2* I +1 and its right child is at index 1.void in-order(struct node *root)
2*1 +2 2. {
3. if(root!= NULL)
4. {
printf("%d",root→ data);
5. in-order(root→ left);
6.
7. in-order(tree→ right);
8. }
9. }
 Post-order traversal: ( L R N )
Algorithm :

1.Traverse the left subtree.


2.Traverse the right subtree.
3.Visit the root node.
Traversal of binary Tree Pseudo-code :
1.void in-order(struct node *root)
2. {
3. if(root!= NULL)
4. {
5. in-order(root→ left);
6.
7. in-order(tree→ right);
printf("%d",root→ data);

8. }
9. }
Draw a binary tree with following traversals :
In-order : B C A E G D H F I J
Pre-order : A B C D E F G H I J
Find the post-order of the tree.

Create BST for the following data, show all steps :


20, 10, 25, 5, 15, 22, 30, 3, 14, 13

 Insertion in BST:
1.if root== null, create BST node with key and return the
node pointer.
2.If root.key > key , recursively insert the new node to the
left subtree.
3.If root.key < key , recursively insert the new node to the
right subtree.
Postorder of tree : C B G E H J I F D A

Binary search tree


 A binary search tree is a binary tree.
 Each node has at most two children.
 The value of the left child is smaller than the parent
node.
 The value of the right child is greater than the parent
node.
 This ordering is applied recursively to left and right
subtrees.
 In BST,No two elements share the same value.
 Efficient for searching, insertion, and deletion operations.
 In-order traversal results in sorted order.
Algorithm else:
// Case 2: One Child
insert(root, key): if root.left is null:
if root is null: return root.right
return new Node(key) else if root.right is null:
return root.left
if key < root.key:
root.left = insert(root.left, key) // Case 3: Two Children
else if key > root.key: successor = findMin(root.right)
root.right = insert(root.right, key) root.key = successor.key
return root root.right = deleteNode(root.right, successor.key)
return root
 Deletion in BST:
Case 1: No Children (Leaf Node) function findMin(node):
If the node to be deleted (N) has no children, delete // Helper function to find the node with the minimum
it by replacing its parent's pointer with a null pointer key in a BST
while node.left is not null:
Case 2: One Child node = node.left
If the node to be deleted (N) has exactly one child, return node
delete it by replacing its parent's pointer with the
pointer to its only child.  Searching in BST:
1. Searching for a key in a Binary Search Tree (BST) involves
Case 3: Two Children traversing the tree in a way that takes advantage of its
If the node to be deleted (N) has two children, find structure.
its in-order successor (S(N)), delete S(N) using Case 1 or 2. The key property of a BST is that for each node:
I. All nodes in its left subtree have keys less than the node's
Case 2, and then replace N with S(N).
key.
II. All nodes in its right subtree have keys greater than the
node's key.

algorithm

function searchBST(root, key):


// Base case: If the tree is empty or the key is found
if root is null or root.key equals key:
return root

// If the key is smaller, search in the left subtree


if key < root.key:
return searchBST(root.left, key)
Algorithm: // If the key is larger, search in the right subtree
else:
function deleteNode(root, key): return searchBST(root.right, key)
if root is null:
return root // Key not found, no deletion
Threaded Binary tree
// Case 1: No Children (Leaf Node)
if root.key equals key and root.left is null and  A binary tree in which some nodes have additional
pointers (threads) that allow for faster in-order traversals.
root.right is null:
 Threads are typically used to avoid the need for
return null recursion or a stack during in-order traversal.
 Threads can be of two types: left threads and right
// Recursive cases threads.
if key < root.key:  A node with a left thread points to its in-order
root.left = deleteNode(root.left, key) predecessor, and a node with a right thread points to its
else if key > root.key: in-order successor.
root.right = deleteNode(root.right, key)
3.Left Right rotation (LR rotation)

4. Right left rotation (RL rotation)

Create an AVL tree for the following elements :


10,9,8,7,6,5,4,3,2,1

AVL TREE

 An AVL (Adelson-Velsky and Landis tree ) tree is a


balanced binary search tree.
 It is a special type of binary search tree.
 In an AVL tree, balance factor of every node is either –1,
0 or +1.
 Balance factor of a node is the difference between the
heights of left and right subtrees of that node.
 Balance factor = height of left subtree – height of right
subtree
 In order to balance a tree, there are four cases of
rotations :
1. Left Left rotation (LL rotation)

Unbalanced LL rotation balanced

2. Right Right rotation (RR rotation)

Unbalanced RR rotation balanced


B-tree
 A B-tree is a self-balancing tree data structure that keeps
data sorted and allows searches, sequential access,
insertions, and deletions in logarithmic time.
 A B-tree of order m is a tree which satisfies the
following properties :
 Every node has at most m children
 Every non-leaf node has at least m/2 children.
 The root has at least two children if it is not a leaf
node.
 A non-leaf node with k children contains k – 1 keys.
 All leaves appear in the same level.

Construct a B-tree of order 3p created by inserting the


following elements
10,20,30,40,50,60,70,80,90

You might also like