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

DS Notes Removed

This document provides an overview of data structures in C programming. It discusses linear data structures like arrays and linked lists, as well as non-linear structures like trees and graphs. It also covers common terminology used in data structures like data, data item, entity, and record. Key concepts like abstract data types, time-space tradeoffs, and asymptotic notation for analyzing algorithms are summarized. Specific data structures like arrays, linked lists, stacks, queues, and sparse matrices are described in more detail.

Uploaded by

SOHAM DIXIT
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

DS Notes Removed

This document provides an overview of data structures in C programming. It discusses linear data structures like arrays and linked lists, as well as non-linear structures like trees and graphs. It also covers common terminology used in data structures like data, data item, entity, and record. Key concepts like abstract data types, time-space tradeoffs, and asymptotic notation for analyzing algorithms are summarized. Specific data structures like arrays, linked lists, stacks, queues, and sparse matrices are described in more detail.

Uploaded by

SOHAM DIXIT
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Author : Abhay Kumar Singh

DATA STRUCTURE USING IN C


UNIT – 1
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[r]) 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

You might also like