The document discusses stacks and queues. It begins by defining a stack as a collection of homogeneous data elements where insertion and deletion occurs at one end, known as the top. The stack follows the LIFO (last in, first out) principle. Common stack operations like push and pop are introduced. Implementing stacks using both arrays and linked lists is covered. Applications of stacks like balancing symbols, recursion, undo operations are mentioned. The document then moves to discussing queues, their applications and implementations. Priority queues and their applications are also briefly covered.
https://github.com/ashim888/dataStructureAndAlgorithm
Stack
Concept and Definition
• Primitive Operations
• Stack as an ADT
• Implementing PUSH and POP operation
• Testing for overflow and underflow conditions
Recursion
• Concept and Definition
• Implementation of:
¬ Multiplication of Natural Numbers
¬ Factorial
¬ Fibonacci Sequences
The Tower of Hanoi
https://github.com/ashim888/dataStructureAndAlgorithm
Stack
Concept and Definition
• Primitive Operations
• Stack as an ADT
• Implementing PUSH and POP operation
• Testing for overflow and underflow conditions
Recursion
• Concept and Definition
• Implementation of:
¬ Multiplication of Natural Numbers
¬ Factorial
¬ Fibonacci Sequences
The Tower of Hanoi
Queues
a. Concept and Definition
b. Queue as an ADT
c. Implementation of Insert and Delete operation of:
• Linear Queue
• Circular Queue
For More:
https://github.com/ashim888/dataStructureAndAlgorithm
http://www.ashimlamichhane.com.np/
Infix to Postfix Conversion Using StackSoumen Santra
Infix to Postfix Conversion Using Stack is one of the most significant example of application of Stack which is an ADT (Abstract Data Type) based on LIFO concept.
Queue is an abstract data structure, somewhat similar to Stacks. Unlike stacks, a queue is open at both its ends. One end is always used to insert data (enqueue) and the other is used to remove data (dequeue). Queue follows First-In-First-Out methodology, i.e., the data item stored first will be accessed first.
Data Structure- Stack operations may involve initializing the stack, using it and then de-initializing it. Apart from these basic stuffs, a stack is used for the following two primary operations −
PUSH, POP, PEEP
Queues
a. Concept and Definition
b. Queue as an ADT
c. Implementation of Insert and Delete operation of:
• Linear Queue
• Circular Queue
For More:
https://github.com/ashim888/dataStructureAndAlgorithm
http://www.ashimlamichhane.com.np/
Infix to Postfix Conversion Using StackSoumen Santra
Infix to Postfix Conversion Using Stack is one of the most significant example of application of Stack which is an ADT (Abstract Data Type) based on LIFO concept.
Queue is an abstract data structure, somewhat similar to Stacks. Unlike stacks, a queue is open at both its ends. One end is always used to insert data (enqueue) and the other is used to remove data (dequeue). Queue follows First-In-First-Out methodology, i.e., the data item stored first will be accessed first.
Data Structure- Stack operations may involve initializing the stack, using it and then de-initializing it. Apart from these basic stuffs, a stack is used for the following two primary operations −
PUSH, POP, PEEP
In computer science, a stack is an abstract data type that serves as a collection of elements, with two main principal operations: push, which adds an element to the collection, and pop, which removes the most recently added element that was not yet removed.
What is Stack, Its Operations, Queue, Circular Queue, Priority QueueBalwant Gorad
Explain Stack and its Concepts, Its Operations, Queue, Circular Queue, Priority Queue. Explain Queue and It's Operations
Data Structures, Abstract Data Types
Vaccine management system project report documentation..pdfKamal Acharya
The Division of Vaccine and Immunization is facing increasing difficulty monitoring vaccines and other commodities distribution once they have been distributed from the national stores. With the introduction of new vaccines, more challenges have been anticipated with this additions posing serious threat to the already over strained vaccine supply chain system in Kenya.
Quality defects in TMT Bars, Possible causes and Potential Solutions.PrashantGoswami42
Maintaining high-quality standards in the production of TMT bars is crucial for ensuring structural integrity in construction. Addressing common defects through careful monitoring, standardized processes, and advanced technology can significantly improve the quality of TMT bars. Continuous training and adherence to quality control measures will also play a pivotal role in minimizing these defects.
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxR&R Consult
CFD analysis is incredibly effective at solving mysteries and improving the performance of complex systems!
Here's a great example: At a large natural gas-fired power plant, where they use waste heat to generate steam and energy, they were puzzled that their boiler wasn't producing as much steam as expected.
R&R and Tetra Engineering Group Inc. were asked to solve the issue with reduced steam production.
An inspection had shown that a significant amount of hot flue gas was bypassing the boiler tubes, where the heat was supposed to be transferred.
R&R Consult conducted a CFD analysis, which revealed that 6.3% of the flue gas was bypassing the boiler tubes without transferring heat. The analysis also showed that the flue gas was instead being directed along the sides of the boiler and between the modules that were supposed to capture the heat. This was the cause of the reduced performance.
Based on our results, Tetra Engineering installed covering plates to reduce the bypass flow. This improved the boiler's performance and increased electricity production.
It is always satisfying when we can help solve complex challenges like this. Do your systems also need a check-up or optimization? Give us a call!
Work done in cooperation with James Malloy and David Moelling from Tetra Engineering.
More examples of our work https://www.r-r-consult.dk/en/cases-en/
TECHNICAL TRAINING MANUAL GENERAL FAMILIARIZATION COURSEDuvanRamosGarzon1
AIRCRAFT GENERAL
The Single Aisle is the most advanced family aircraft in service today, with fly-by-wire flight controls.
The A318, A319, A320 and A321 are twin-engine subsonic medium range aircraft.
The family offers a choice of engines
Democratizing Fuzzing at Scale by Abhishek Aryaabh.arya
Presented at NUS: Fuzzing and Software Security Summer School 2024
This keynote talks about the democratization of fuzzing at scale, highlighting the collaboration between open source communities, academia, and industry to advance the field of fuzzing. It delves into the history of fuzzing, the development of scalable fuzzing platforms, and the empowerment of community-driven research. The talk will further discuss recent advancements leveraging AI/ML and offer insights into the future evolution of the fuzzing landscape.
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)MdTanvirMahtab2
This presentation is about the working procedure of Shahjalal Fertilizer Company Limited (SFCL). A Govt. owned Company of Bangladesh Chemical Industries Corporation under Ministry of Industries.
Cosmetic shop management system project report.pdfKamal Acharya
Buying new cosmetic products is difficult. It can even be scary for those who have sensitive skin and are prone to skin trouble. The information needed to alleviate this problem is on the back of each product, but it's thought to interpret those ingredient lists unless you have a background in chemistry.
Instead of buying and hoping for the best, we can use data science to help us predict which products may be good fits for us. It includes various function programs to do the above mentioned tasks.
Data file handling has been effectively used in the program.
The automated cosmetic shop management system should deal with the automation of general workflow and administration process of the shop. The main processes of the system focus on customer's request where the system is able to search the most appropriate products and deliver it to the customers. It should help the employees to quickly identify the list of cosmetic product that have reached the minimum quantity and also keep a track of expired date for each cosmetic product. It should help the employees to find the rack number in which the product is placed.It is also Faster and more efficient way.
Welcome to WIPAC Monthly the magazine brought to you by the LinkedIn Group Water Industry Process Automation & Control.
In this month's edition, along with this month's industry news to celebrate the 13 years since the group was created we have articles including
A case study of the used of Advanced Process Control at the Wastewater Treatment works at Lleida in Spain
A look back on an article on smart wastewater networks in order to see how the industry has measured up in the interim around the adoption of Digital Transformation in the Water Industry.
Water scarcity is the lack of fresh water resources to meet the standard water demand. There are two type of water scarcity. One is physical. The other is economic water scarcity.
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Dr.Costas Sachpazis
Terzaghi's soil bearing capacity theory, developed by Karl Terzaghi, is a fundamental principle in geotechnical engineering used to determine the bearing capacity of shallow foundations. This theory provides a method to calculate the ultimate bearing capacity of soil, which is the maximum load per unit area that the soil can support without undergoing shear failure. The Calculation HTML Code included.
Forklift Classes Overview by Intella PartsIntella Parts
Discover the different forklift classes and their specific applications. Learn how to choose the right forklift for your needs to ensure safety, efficiency, and compliance in your operations.
For more technical information, visit our website https://intellaparts.com
Overview of the fundamental roles in Hydropower generation and the components involved in wider Electrical Engineering.
This paper presents the design and construction of hydroelectric dams from the hydrologist’s survey of the valley before construction, all aspects and involved disciplines, fluid dynamics, structural engineering, generation and mains frequency regulation to the very transmission of power through the network in the United Kingdom.
Author: Robbie Edward Sayers
Collaborators and co editors: Charlie Sims and Connor Healey.
(C) 2024 Robbie E. Sayers
1. Unit-III
Topics to be covered
Stacks and Queues: Introduction to stacks
applications of stacks
implementation and comparison of stack implementations.
Introduction to queues
applications of queues and implementations
Priority Queues and applications
S. Durga Devi ,CSE,CBIT
2. Stacks
Definition - A stack is an ordered collection of homogeneous data
elements, where the insertion and deletion takes place at one end,
known as TOP.
The stack is also called LAST IN FIRST OUT(LIFO)
It means: the element which is inserted last must be deleted first
Example
1. pile of plates in cafeteria
2. stack of coins
S. Durga Devi ,CSE,CBIT
3. Stack maintains a pointer called top, which keeps track of the top
most element in the stack.
Any insertions or deletions should be based upon the value of top.
It works on the basis of LIFO (Last in First out).
According to the definition, new elements are inserted from top
and the elements are deleted from same end i.e again top.
This suggests that the element inserted most recently can only be
deleted.
In the stack, the elements are removed in the reverse order of that
in which they were added to the stack i.e last element inserted is
to be deleted first.
So it is called last in first out.
Stack has structured with two operations
1. push- insertion adding elements on to a stack
2. Pop- deletion removing element from the stack
S. Durga Devi , CSE, CBIT
4. Basic operations:
The basic operations are insertion, deletion ,display.
In stacks, special terms are given for insert and delete. i.e push
for insert and pop is for delete.
Push: inserting or adding element into the stack is called push.
Pop: deleting or removing element from the stack is called
pop.
S. Durga Devi ,CSE,CBIT
5. Elements are inserted in the order as A,B,C,D,E
It represents the stack of 5 elements.
The top most element in the stack is E
If we want to deleteelement E has to be deleted first
S. Durga Devi ,CSE,CBIT
8. ADT For Stack
ADT for stack
int stack[5],top;
void push();
void pop();
void display();
int size();
void isEmpty();
void isFull();
S. Durga Devi ,CSE,CBIT
9. Applications of stacks
Balancing symbols
Parenthesis matching.
Evaluation of postfix expressions.
Infix to prefix conversions.
Infix to postfix conversions.
Implementing function calls(Recursion)
Web browser history
Undo operations in text editors
Matching tags in HTML and XML
Quick sort.
S. Durga Devi ,CSE,CBIT
10. Implementing stack using arrays
Algorithm for inserting element into the stack:
Algorithm push()
1. if top=(SIZE-1)
then write (‘stack overflow’)
else
2. read item or data
3. top←top+1
4. stack[top]← item
5. stop
S. Durga Devi ,CSE,CBIT
11. Explanation:
The stack is of size max. This procedure inserts an element
item on to the top of a stack which is represented by an
array stack.
The first step of this algorithm checks for an overflow
condition.
Overflow means inserting element into a stack which is
full.
If the top value reaches to maximum size of the stack then
elements cannot be inserted into the stack i.e. stack is full.
Otherwise top is incremented by one and element is
inserted into the stack.
S. Durga Devi ,CSE,CBIT
12. Algorithm to delete elements from the stack:
Algorithm pop()
1. if top=-1
then write (‘stack underflow’)
else
2. item ← stack[top]
3. top ← top-1
S. Durga Devi ,CSE,CBIT
13. Explanation:
This procedure deletes an element from the stack.
The first step of this algorithm checks for
underflow condition.
If the top value is -1 then stack is empty.
Empty stack is known as underflow.
Takeout the element from the location where, the
top is pointing and then decrement top by one.
S. Durga Devi ,CSE,CBIT
14. Display of stack:
Printing the contents of stack after push and pop
operations.
Algorithm print()
1. if top=-1
then write (‘stack empty’)
2. Repeat for i ← top to 0
print(stack[i])
3. stop
S. Durga Devi ,CSE,CBIT
15. Space complexity
Time complexity of push(), pop(),size(), isEmpty(), isFull()
will take O(1).
Limitation in stack using array is that maximum size of the
stack must be pre defined and it cannot be changed(fixed).
When trying to add elements in the stack when the stack is
full will rise the exception.
S. Durga Devi ,CSE,CBIT
16. Consider size of the stack is 4
Insert following elements A,B,C,D
Representing Stack with Dynamic array
S. Durga Devi ,CSE,CBIT
A
A B
A B C
A B C D
A B C D E
Stack is full when E is inserted create a new stack with double size
and copy all the old stack elements to new
stack and named it as old stack
17. Disadvantage of using an array to implement a stack or queue
is the wastage of space.
Implementing stacks as linked lists provides a feasibility on
the number of nodes by dynamically growing stacks, as a
linked list is a dynamic data structure.
The stack can grow or shrink as the program demands it to.
A variable top always points to top element of the stack.
top = NULL specifies stack is empty.
Representing Stack with Linked List
S. Durga Devi ,CSE,CBIT
18. In this representation, first node in the list is last
inserted element hence top must points to the first
element on the stack
Last node in the list is the first inserted element in the
stack.
Thus, push operation always adds the new element at
front of the list
And pop operation removes the element at front of
the list.
Size of the stack not required.
Test for overflow is not applicable in this case.
S. Durga Devi ,CSE,CBIT
19. 10 NULL
1500
1800
1200
1400
20 1400
30 1200
40 1800
50 1500 1100
top
Example:
The following list consists of five cells, each of which holds a data object
and a link to another cell.
A variable, top, holds the address of the first cell in the list.
S. Durga Devi ,CSE,CBIT
20. /* write a c program to implement stack using linked list */
#include<stdio.h> #include<malloc.h> #include<stdlib.h>
int push(); int pop(); int display();
int choice,i,item;
struct node {
int data;
struct node *link;
}*top,*new,*ptr;
main() { top=NULL;
printf("n***Select Menu***n");
while(1) {
printf("n1.Push n2.Pop n3.Display n4.Exitn5.Count");
printf("nnEnter ur choice: ");
scanf("%d",&choice);
switch(choice) {
case 1: push(); break;
case 2: pop(); break;
case 3: display(); break;
case 4: exit(0);
case 5: count(); break;
default: printf("nWrong choice");
}/* end of switch */
}/* end of while */
}/* end of main */ S. Durga Devi ,CSE,CBIT
21. int push()
{
new=malloc(sizeof(struct node));
printf("nEnter the item: ");
scanf("%d",&item);
new->data=item;
if(top==NULL)
{
new->link=NULL;
}
else
{
new->link=top;
}
top=new;
return;
}/* end of insertion */
int pop()
{
if(top = = NULL)
{
printf("nnStack is empty");
return;
}//if
else
{
printf("nnThe deleted element
is: %d",top->data);
top=top->link;
}
return;
}/* end of pop() */
S. Durga Devi ,CSE,CBIT
22. int display()
{
ptr=top;
if(top= =NULL)
{
printf("nThe list is empty");
return;
}
printf("nThe elements in the stact are: ");
while(ptr!=NULL)
{
printf("n %d",ptr->data);
ptr=ptr->link;
}/* end of while */
return;
}/* end of display() */
int count()
{
int count=1;
ptr=top;
if(top = = NULL)
{
printf("nThe list is empty");
return;
}
while(ptr->link!=NULL)
{
++count;
ptr=ptr->link;
}
printf("nnThe number of elements in
the stack are: %d",count);
return;
}/* end of count */
S. Durga Devi ,CSE,CBIT
23. Applications of stacks
Balancing symbols ({},(),””)
Evaluation of postfix expressions.
Infix to postfix conversions.
Infix to prefix conversions.
Implementing function calls(Recursion)
Web browser history
Undo operations in text editors
Matching tags in HTML and XML
Quick sort.
S. Durga Devi ,CSE,CBIT
24. 1.Parenthesis matching
The objective of this function is to check the
matching of parenthesis in an expression
i.e
In an expression the no of left parenthesis must be
equal to no: of right parenthesis.
Ex: ((A+B)*C)
This is a valid expression because in this no of left
parenthesis (2) = no: of right parenthesis (2).
S. Durga Devi ,CSE,CBIT
25. Conversion of expressions
Arithmetic expressions can be represented in three ways:
Infix notation
Prefix notation
Postfix notation
1. Infix notation-In which operatorshould be placed in between the two operands.
Example- A+B C-D E*F G/H.
2. Prefix notation(polish notation)-
• Operatorpreceded by the operand is called prefix notation
Examples
+AB -CD *EF GH.
3. Postfix notation(reverse polish notationor suffix notation)-
• Operator should be placed after operands.
AB+ CD- EF* GH
S. Durga Devi ,CSE,CBIT
26. Notations – Conversions
Considerthe infix expression: 2 + 3 * (5 – 7) / 9
Let us insert implicit parentheses
(2 + ((3 * (5 – 7)) / 9))
Transferthe operators to the beginning of parentheses
(+ 2 (/ (* 3 (– 5 7)) 9))
Removethe parentheses: + 2 / * 3 – 5 7 9
This is the equivalentprefix expression.
Transferthe operators to the end of parentheses
(2 ((3 (5 7 –) *) 9 /) +)
Removethe parentheses: 2 3 5 7 – * 9 / +
This is the equivalentpostfixexpression.
S. Durga Devi ,CSE,CBIT
28. Infix to post fix(RPN) Conversion
Algorithm to convertinfix expressionto postfixexpression(RPN):
1. Declare a stack and postfix array(output: postfix expression)
2. Repeat the following steps until the end of the infix expression is reached.
1. Get input token (constant, variable, arithmetic operator,left
parenthesis, right parenthesis) in the infix expression.
2. If the token is
2.1 A left parenthesis: Push it onto the stack.
2.2 A right parenthesis:
2.2.1 Pop the stack elements and add to postfix array until a left
parenthesisis on the top of the stack.
2.2.2 Pop the left parenthesis also, but do not add to postfix array
2.3 An operator:
2.3.1 While the stack is nonemptyand token has lower or equal
priority than stack top element, pop and add to postfix array.
2.3.2 Push token onto the stack.
2.4 An operand: add to postfix array
3. When the end of the infix expression is reached, pop the stack elements
and add to postfix array until the stack is empty.
(Note: Left parenthesis in the stack has lowest priority) S. Durga Devi ,CSE,CBIT
29. Note
• the lower precedence operator never placed on
top of the higher precedence.
• (A-B)*(D/E)
S. Durga Devi ,CSE,CBIT
31. Infix expression- (A+B)^C-(D*E)/F
Infix Stack Post fix
( ( Empty
A ( A
+ (+ A
B (+ AB
) Empty AB+
^ ^ AB+
C ^ AB+C
- - AB+C^
( -( AB+C^
D -( AB+C^D
* -(* AB+C^D
E -(* AB+C^DE
) - AB+C^DE*
/ -/ AB+C^DE*
F -/ AB+C^DE*F
Empty AB+C^DE*F/- S. Durga Devi ,CSE
32. Postfix (reverse polish notation) expression
evaluation
• Algorithm
1.Scan expression from left to right and repeat steps 2 and 3 for each element
of expression.
2. If an operand is encountered,push it on to stack.
3.If an operatorop1 is encounteredthen
3.1 remove the top two elements of stack, where A is the top and B is the next
top element.
3.2 evaluate B op1 A
3.3 push the result back on to the stack.
4. set the top value on stack.
5. stop
S. Durga Devi ,CSE,CBIT
35. #include<stdio.h>
#include<ctype.h>
#include<string.h>
int priority(char c);
int push(char c);
int pop();
static char str[30];
int top=-1;
void main()
{
char in[30],post[30],ch;
int i,j,l;
printf("enter the string");
gets(in);
l=strlen(in);
Write a C program to convert infix to postfix evaluation
S. Durga Devi ,CSE,CBIT
37. A queueis a linear data structurein which insertion take place from one end called re
end and deletionstake place from otherend called front end i.e insertion and deletion
take place from different ends.
The principleused to in queue is FIFO.(First In First Out)
FIFO- the element which is inserted First must be deleted First.
In a queue thereare two variables one is the rear and otherone is front.
the element must be always added at rear end and removed from the front.
Basic operationson queue:
The operationsthat can be performed on queue are
Insertion Enqueue
Deletion Dequeue
Display
Queues
Front rear
S. Durga Devi ,CSE,CBIT
42. FrontRear
Front
Rear
Front
Rear
•A queueis like a line of peoplewaiting for
• a bank teller.The queuehas a front and a rear.
New peoplemust enter the queueat the rear.
When an item is taken from the queue, it always comes from the front.
S. Durga Devi ,CSE,CBIT
43. QueueADT
• basic queue operations:
– add (enqueue): Add an element to the back.
– remove (dequeue): Remove the front element.
– peek: Examine the element at the front.
– isEmpty(): check whether queue is empty or not
– isFull() : whether queue is full or not
S. Durga Devi ,CSE,CBIT
44. • Different types of queues
1. Linear queue or queue
2. Circular queue
3. Doubly ended queue( dequeue)
4. Priority queue
S. Durga Devi ,CSE,CBIT
45. Working of a linear queue using an array
i) Initially front=rear= -1. It indicates queue is empty.
0 1 2 3 4
front=rear=-1
0 1 2 3 4
ii) Add 10
10
front rear
0 2 3 4
iii) Add 20
front rear
1
10 20
0 2 3 4
iv) Add 30
front rear
1
10 20 30
0 2 3 4
v) Add 40
front rear
1
10 20 30 40
S. Durga Devi ,CSE,CBIT
46. 0 2 3 4
vi) Add 50
front rear
1
10 20 30 40 50
0 2 3 4
vii) Add 60 (overflow)
front rear
1
10 20 30 40 50
0 2 3 4
viii) delete (10 is removed)
front rear
1
20 30 40 50
0
front rear
1
30 40 50
ix) delete (20 is removed)
2 3 4
S. Durga Devi ,CSE,CBIT
47. 0
front rear
1
40 50
x) delete (30 is removed)
2 3 4 0
front rear
1
50
xi) delete (40 is removed)
2 3 4
0
front=rear=-1
1
ix) delete (underflow)
2 3 40
front=rear=-1
1
xii) delete (50 is removed)
2 3 4
S. Durga Devi ,CSE,CBIT
48. Implementation of queue using array
Algorithm insert( )
1. If rear ≥ size-1
then write (‘overflow’)
2. Read item
3. rear← rear + 1
4. queue[rear]← item
5. If(front==-1)
6. front++;
7. stop
Explanation:
This procedureadds an element item to the
queue.
First it checks for an overflow condition.
If the rear value reaches or exceeds size of th
queue
then elements cannot be inserted into the queue
ie. Overflow.
Whenever element is inserted into the queue,
rear is increment by one
and place the element in the location
where rear is pointing.
S. Durga Devi ,CSE,CBIT
49. Algorithm to delete element from the queue
Algorithm delete()
1. If (front= = -1)or (front> rear)
then write (‘queueunderflow’)
item ← queue[front]
2. front ← front + 1
Explanation:
This procedure deletes an element from the queue.
The first step of this algorithm checks for underflow condition.
If the front value is -1or greater than rear then queue is empty.
Take out the element from the location where, the front is pointing and
store it in the variable, then increment front by one.
S. Durga Devi ,CSE,CBIT
50. Algorithm to display elements in a queue
1. if((front==-1)||(front>rear))
1.1 print statck is Underflow
2. Else
2.1 repeat for i->front to rear
2.2. print queue[i];
Drawback in queue
In a queue when the rear pointer reaches to the end of the queue,
insertion would be denied even if room is available at the front
one way to remove this is using the circular queue
S. Durga Devi ,CSE,CBIT
51. Program: implementation of queue using array
# include <stdio.h>
# define size 4
void insertion();
void deletion();
void display();
int front=-1,rear=-1,item,choice,queue[size];
void main()
{clrscr();
while(1)
{
printf("n*** MENU ***n 1. INSERTIONn 2. DELETIONn
3.TRAVERSEn 4. EXITn");
printf("enter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:insertion();
break;
case 2:deletion();
break;
case 3:display();
break;
case 4:exit();
default:printf("*** wrong choice ***n");}}}
S. Durga Devi ,CSE,CBIT
52. void insertion()
{
if(rear>=size-1)
printf("*** queue is full ***n");
else
{
printf("enter item into queue:");
scanf("%d",&item);
rear++;
queue[rear]=item;
if(front==-1)
front++;
} }
void deletion()
{
if((front==-1)||(front>rear))
printf("*** queue is empty ***n");
else
{
item=queue[front];
front++;
printf("the deleted item from queue is
%dn",item);
}
}
void display(){
int i;
if((front==-1)||(front>rear))
printf("*** queue is empty ***n");
else
{
printf("n elements in queue:- ");
for(i=front;i<=rear;i++)
printf("%d ",queue[i]);
}} S. Durga Devi ,CSE,CBIT
55. • How to test whether circular queue is empty or full?
• The circular q is controlled by the MOD operation.
• Circular queue is empty
when front =-1
rear=-1
Circular queue is full
front = (rear+1)% SIZE
S. Durga Devi ,CSE,CBIT
56. Implementation of circular queue using array
• Algorithm for insertion
1.if((front == 0 && rear == SIZE-1) || (front == (rear+1)%size)
2.printf("Queue Overflow n");
return;
3.if (front == -1) /*If queue is empty */
3.1 front = 0;
3.2 rear = 0;
4.else
5.if(rear == SIZE-1)/*rear is at last position of queue */
6.rear = 0;
7. else
8.rear = rear+1;
9.Read item
10.cq[rear] = item ;
11.end
S. Durga Devi ,CSE,CBIT
57. • Algorithm for deletion
• 1.if (front == -1)
2.printf("Queue Underflown")
return
3.if(front == rear) /* queue has only one element */
3.1front = -1;
3.2rear=-1;
4.else
5.if(front == SIZE-1)
• front = 0;
6.else
7.front = front+1;
8.Stop
S. Durga Devi ,CSE,CBIT
58. int insert(){
int item;
if((front == 0 && rear == SIZE-1) || (front == rear+1))
{
printf("Queue Overflow n");
return;}
if (front == -1) /*If queue is empty */
{
front = 0;
rear = 0;
}
else
if(rear == SIZE-1)/*rear is at last position of queue */
rear = 0;
else
rear = rear+1;
printf("Input the element for insertion in queue : ");
scanf("%d", &item);
cq[rear] = item ;
printf("the element %d at %d position and
front=%d,rear=%dn",cq[rear],rear,front,rear);
return;
}/*End of insert()*/
S. Durga Devi ,CSE,CBIT
59. int del()
{
if (front == -1)
{
printf("Queue Underflown");
return ;
}
printf("Element deleted from queue is :
%dn",cq[front]);
if(front == rear) /* queue has only one
element */
{
front = -1;
rear=-1;
}
else
if(front == SIZE-1)
front = 0;
else
front = front+1;
printf("front=%d,rear=%dn",front,rear)
;
return;
}/*End of del() */
Deletion
S. Durga Devi ,CSE,CBIT
60. display()
int display(){
int front_pos = front,rear_pos = rear;
if(front == -1){
printf("Queue is emptyn");
Return;}
printf("Queue elements :n");
if( front_pos <= rear_pos )
while(front_pos <= rear_pos){
printf("%d ",cq[front_pos]);
front_pos++;}
else{
while(front_pos <= SIZE-1){
printf("%d ",cq[front_pos]);
front_pos++;}
front_pos = 0;
while(front_pos <= rear_pos){
printf("%d ",cq[front_pos]);
front_pos++;}}/*End of else */
printf("n");
return;
}/*End of display() */
S. Durga Devi ,CSE,CBIT
61. Applications of queues
There are several applications of queues in computer science.
1. Implement various aspects of operating systems.
2. CPU scheduling in Multiprogramming environment- single CPU has to serve
more than one program simultaneously.
3. Round Robin CPU scheduling algorithm.
4. In operating System maintains a queue of processes that are ready to process or
that are waiting for particular event to occur.
5. Computer system maintains a buffer and is implemented as a queue.
6. Printer
7. Call waiting when you are attending other call
8. a file server in a computer network handles file access request from many clients
throughout the network. Servers have a limited capacity to service request from
clients. when that capacity is exceeded, client requests wait in queues
9. This type of data structure is used in time sharing systems where many user jobs will
be waiting in the system queue for processing. These jobs may request the
services of CPU, main memory or external devices such as printer.
10. Radix sort implemented using queue.
S. Durga Devi ,CSE,CBIT
62. Queues in computer science
• Operating systems:
– queue of print jobs to send to the printer
– queue of programs / processes to be run
– queue of network data packets to send
• Programming:
– modeling a line of customers or clients
– storing a queue of computations to be performed in
order
• Real world examples:
– people on an escalator or waiting in a line
– cars at a gas station (or on an assembly line)
S. Durga Devi ,CSE,CBIT
63. Radix sort
• This algorithm sorts the elements from least significant digit to
most significant digit
• As you know the numbers are formed with digits 0 to 9 so we need
10 buckets labelled 0 to 9 to sort the unsorted numbers.
• First find the largest number in the given unsorted elements and
count its digits.
• If largest number has n digits, the algorithm could be completed in
n number of passes to sort the numbers in specified order.
• Number of passes (bucket sort stages) will depend on the number
of digits in the maximum value
64. Example : 100, 54,355,102,43,10,287,5
0 1 2 3 4 5 6 7
100 54 355 102 43 10 287 5
Take buckets numbered from 0 to 9
Take first number 100 has 0 in the 1st place so put that number in 0th bucket
54 has 4 in the 1st place so put that number in 4th bucket
0 1 2 3 4 5 6 7 8 9
72. 0 1 2 3 4 5 6 7
100 54 355 102 43 10 287 5
0 1 2 3 4 5 6 7 8 9
100 54 355102 43
10
287
5
Take out the elements from the buckets starts from 0th bucket to 9th bucket
Place it in an array
73. 0 1 2 3 4 5 6 7
100 54 355 102 43 10 287 5
0 1 2 3 4 5 6 7 8 9
100 54 355102 43
10
287
5
Take out the elements from the buckets starts from 0th bucket to 9th bucket
Place it in an array
0 1 2 3 4 5 6 7
100
74. 0 1 2 3 4 5 6 7
100 54 355 102 43 10 287 5
0 1 2 3 4 5 6 7 8 9
54 355102 43
10 287
5
Take out the elements from the buckets starts from 0th bucket to 9th bucket
Place it in an array
0 1 2 3 4 5 6 7
100
75. 0 1 2 3 4 5 6 7
100 54 355 102 43 10 287 5
0 1 2 3 4 5 6 7 8 9
54 355102 43
287
5
Take out the elements from the buckets starts from 0th bucket to 9th bucket
Place it in an array
0 1 2 3 4 5 6 7
100 10
76. 0 1 2 3 4 5 6 7
100 54 355 102 43 10 287 5
0 1 2 3 4 5 6 7 8 9
54 355102 43
287
5
Take out the elements from the buckets starts from 0th bucket to 9th bucket
Place it in an array
0 1 2 3 4 5 6 7
100 10 102
77. 0 1 2 3 4 5 6 7
100 54 355 102 43 10 287 5
0 1 2 3 4 5 6 7 8 9
54 355
43
287
5
Take out the elements from the buckets starts from 0th bucket to 9th bucket
Place it in an array
0 1 2 3 4 5 6 7
100 10 102
78. 0 1 2 3 4 5 6 7
100 54 355 102 43 10 287 5
0 1 2 3 4 5 6 7 8 9
54 355
43
287
5
Take out the elements from the buckets starts from 0th bucket to 9th bucket
Place it in an array
0 1 2 3 4 5 6 7
100 10 102 43
79. 0 1 2 3 4 5 6 7
100 54 355 102 43 10 287 5
0 1 2 3 4 5 6 7 8 9
54 355 287
5
Take out the elements from the buckets starts from 0th bucket to 9th bucket
Place it in an array
0 1 2 3 4 5 6 7
100 10 102 43
80. 0 1 2 3 4 5 6 7
100 54 355 102 43 10 287 5
0 1 2 3 4 5 6 7 8 9
54 355 287
5
Take out the elements from the buckets starts from 0th bucket to 9th bucket
Place it in an array
0 1 2 3 4 5 6 7
100 10 102 43 54
81. 0 1 2 3 4 5 6 7
100 54 355 102 43 10 287 5
0 1 2 3 4 5 6 7 8 9
355 287
5
Take out the elements from the buckets starts from 0th bucket to 9th bucket
Place it in an array
0 1 2 3 4 5 6 7
100 10 102 43 54
82. 0 1 2 3 4 5 6 7
100 54 355 102 43 10 287 5
0 1 2 3 4 5 6 7 8 9
355 287
5
Take out the elements from the buckets starts from 0th bucket to 9th bucket
Place it in an array
0 1 2 3 4 5 6 7
100 10 102 43 54 355
83. 0 1 2 3 4 5 6 7
100 54 355 102 43 10 287 5
0 1 2 3 4 5 6 7 8 9
287
5
Take out the elements from the buckets starts from 0th bucket to 9th bucket
Place it in an array
0 1 2 3 4 5 6 7
100 10 102 43 54 355
84. 0 1 2 3 4 5 6 7
100 54 355 102 43 10 287 5
0 1 2 3 4 5 6 7 8 9
287
5
Take out the elements from the buckets starts from 0th bucket to 9th bucket
Place it in an array
0 1 2 3 4 5 6 7
100 10 102 43 54 355 5
85. 0 1 2 3 4 5 6 7
100 54 355 102 43 10 287 5
0 1 2 3 4 5 6 7 8 9
287
Take out the elements from the buckets starts from 0th bucket to 9th bucket
Place it in an array
0 1 2 3 4 5 6 7
100 10 102 43 54 355 5
86. 0 1 2 3 4 5 6 7
100 54 355 102 43 10 287 5
0 1 2 3 4 5 6 7 8 9
287
Take out the elements from the buckets starts from 0th bucket to 9th bucket
Place it in an array
0 1 2 3 4 5 6 7
100 10 102 43 54 355 5 287
87. 0 1 2 3 4 5 6 7
100 54 355 102 43 10 287 5
0 1 2 3 4 5 6 7 8 9
Take out the elements from the buckets starts from 0th bucket to 9th bucket
Place it in an array
0 1 2 3 4 5 6 7
100 10 102 43 54 355 5 287
PASS-1 completed
88. 0 1 2 3 4 5 6 7
100 10 102 43 54 355 5 287
PASS-2
consider ten’s place and place it into its corresponding bucket number
100 has 0 in its ten’s place so put 100 in 0th bucket
0 1 2 3 4 5 6 7 8 9
100
97. 0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7
100 102 05 10 43 54 355 287
PASS-3
Now consider 100th place digit and put it in corresponding bucket
100 number has 1 in its hundred’s place so put it in bucket 1
100
107. Circular queue using array
# include<stdio.h>
#include<stdlib.h>
# define SIZE 4
int insert();
int del();
int display();
int cq[SIZE];
int front = -1;
int rear = -1;
main(){
while(1){
printf("1.Insertn");
printf("2.Deleten");
printf("3.Displayn");
printf("4.Quitn");
printf("Enter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1 :
insert();
break;
case 2 :
del();
break;
case 3:
display();
break;
case 4:
exit(0);
default:
printf("Wrong choicen");
}/*End of switch*/
}/*End of while */
}/*End of main()*/
108. int insert(){
int item;
if((front == 0 && rear == SIZE-1) || (front == rear+1))
{
printf("Queue Overflow n");
return;}
if (front == -1) /*If queue is empty */
{
front = 0;
rear = 0;
}
else
if(rear == SIZE-1)/*rear is at last position of queue */
rear = 0;
else
rear = rear+1;
printf("Input the element for insertion in queue : ");
scanf("%d", &item);
cq[rear] = item ;
printf("the element %d at %d position and
front=%d,rear=%dn",cq[rear],rear,front,rear);
return;
}/*End of insert()*/
111. Dictionary ADT
• The dictionary ADT models a
searchable collection of key-
element entries
• The main operations of a
dictionary are searching, inserting,
and deleting items
• Multiple items with the same key
are allowed
• Applications:
– word-definitionpairs
– credit card authorizations
– DNS mapping of host names (e.g.,
datastructures.net) to internet IP
addresses (e.g., 128.148.34.101)
• Dictionary ADT methods:
– find(k): if the dictionary has
an entry with key k, returns
it, else, returns null
– findAll(k): returns an
iterator of all entries with
key k
– insert(k, o): inserts and
returns the entry (k, o)
– remove(e): remove the
entry e from the dictionary
– entries(): returns an iterator
of the entries in the
dictionary
– size(), isEmpty()
113. The findAll(k) Algorithm
Algorithm findAll(k):
Input: A key k
Output: An iterator of entries with key equal to k
Create an initially-empty list L
B = D.entries()
while B.hasNext() do
e = B.next()
if e.key() = k then
L.insertLast(e)
return L.elements()
114. The insert and remove Methods
Algorithm insert(k,v):
Input: A key k and value v
Output: The entry (k,v) added to D
Create a new entry e = (k,v)
S.insertLast(e) {S is unordered}
return e
Algorithm remove(e):
Input: An entry e
Output: The removed entry e or null if e was not in D
{We don’t assume here that e stores its location in S}
B = S.positions()
while B.hasNext() do
p = B.next()
if p.element() = e then
S.remove(p)
return e
return null {there is no entry e in D}
115. A List-Based Dictionary
• A log file or audit trail is a dictionary implemented by means of an
unsorted sequence
– We store the items of the dictionaryin a sequence (based on a doubly-
linked list or array), in arbitrary order
• Performance:
– insert takes O(1) time since we can insert the new item at the beginning
or at the end of the sequence
– find and remove take O(n) time since in the worst case (the item is not
found) we traverse the entire sequence to look for an item with the given
key
• The log file is effective only for dictionaries of small size or for
dictionaries on which insertions are the mostcommon operations,
while searches and removals are rarely performed (e.g., historical
record of logins to a workstation)
116. Hash Table Implementation
• We can also create a hash-table dictionary
implementation.
• If we use separate chaining to handle
collisions,then each operation can be
delegated to a list-based dictionary stored at
each hash table cell.
120. Linear Search Implementation using non recursive method
#include<stdio.h>
#define SIZE 8
int linear_search(int a[], int target, int size);
void read_array(int a[], int size);
int main(void) {
int x[SIZE], target;
int index;
read_array(x, SIZE);
printf("EnterElement to search for: ");
scanf("%d", &target);
index = linear_search(x, target, SIZE);
if (index!= 0)
printf("Target was found at index %dn",index);
else
printf("Sorry, target item was not found");
return 0;
}
void read_array (int a[],int size) {
int i;
printf("Enter %d integer numbers separated by
blanksn> ", size);
for (i = 0; i < size; ++i)
scanf("%d", &a[i]);
}
/* Searches for an target in an array using
Linear search;
* Returns index of target or -1 if not found */
int linear_search(int a[], int target, int size)
{
int i,loc=0;
for(i=0;i<SIZE;i++)
{
if(target==a[i])
return ++loc;
else
loc++;
}
return 0;
}
121. /* C program that use recursivefunction to perform the Linear
Search for a Key value in a given listof integers*/
#include<stdio.h> #define SIZE 5
int linearSearch(intarray[], int index, int length, int value);
void main() {
int list[SIZE],element,i,target,index=0;
printf("nnEnter%d integer elements: ",SIZE);
for(i = 0; i < SIZE; i++) {
scanf("%d",&list[i]);
}
printf("nEntertarget element to be searched: ");
scanf("%d",&target);
element = linearSearch(list,index,SIZE,target);
if( element != -1 )
printf("nElement is found at %d location",element+1);
else
printf("Element is not found...");
}
122. int linearSearch(intarray[], int index,int length, int value)
{
if(index>length-1)
return -1;
else
if (array[index]==value)
return index;
else
return linearSearch(array,index+1,length,
value);
}
124. Efficiency of Linear Search
• The efficiency of an algorithm is measured using the big O notation
( O stands for order of )
• Big O Notation
– Indicates the worst-case run time (maximum time taken for
execution) for an algorithm
– In other words, how hard an algorithm has to work to solve a
problem
For Linear Search algorithm :O(n)
125. Binary Search: The search starts at middle of a sorted array, if middle
is equal to target element search is successful otherwise it determines
which half to be continue to search on that basis.
The algorithm starts searching with the mid element.
mid=(first+ last)/2
If the item is equal to mid then search is successful.
If the item is less than the mid element, it starts over searching the first
half of the list.
If the item is greater than the mid element, the search starts over the
second half of the list.
It then continues halving the list until the item is found.
Each iteration eliminates half of the remaining elements.
It is faster than the linear search.
It works only on SORTED array.
Thus, there is a performance penalty for sorting the array.
The Time complexity of Binary Search is O(log N).
126.
127. /* C program that use recursivefunction to perform the Binary Search
for a Key valuein a given list of integers*/
#include<stdio.h> #define SIZE 8
int binary_search(int list[], int low, int high, int target);
void main() {
int list[SIZE], target, index,i;
printf("Enter%d elements in ascending or descendingorder: ",SIZE);
for(i=0;i<SIZE;i++)
scanf("%d",&list[i]);
printf("Enteran element that is to be searched: ");
scanf("%d", &target);
index = binary_search(list,0, SIZE-1, target);
if (index != -1)
printf("nTarget was found at index: %d ", index+1);
else
printf("Sorry, target item was not found");
}
128. int binary_search(int list[], int low, int high, int target)
{
int middle;
if (low > high)
return -1;
middle = (low + high)/2;
if (list[middle]== target)
return (middle);
else
if (list[middle]< target)
return binary_search(list,middle+1,high,target);
else
return binary_search(list,low,middle-1,target);
}
129. /* C program that use non recursivefunctionto perform the Binary
Search for a Key value in a given listof integers*/
#include<stdio.h>
#define SIZE 8
int binary_search(int list[], int low, int high, int target);
voidmain() {
int list[SIZE], target, index,i;
printf(“nenterthe array elements”);
for(i=0;i<SIZE;i++)
scanf("%d",&list[i]);
printf(“n enter the target element");
scanf("%d", &target);
index = binary_search(list,0, SIZE-1, target);
if (index != -1)
printf("nelement atlocation%d ", index+1);
else
printf("Sorry, target item was not found");
getch();
}
130. int binary_search(int a[],int low, int high, int target)
{
int middle;
while(low<=high)
{
middle=(low+high)/2;
if(target<a[middle])
high=middle-1;
else if(target>a[middle])
low=middle+1;
else
return middle;
}//while
return -1;
}//binary_search()
132. Why hashing?
• Internet has grown to millions of users and terabytes of data every
data.
• It is impossible to find anything in the internet, unless we develop a
new data structure to store and access the data very quickly.
• The amount of time required to look up an element in an array or
linked list is either O(logn) or O(n) based on the list is sorted or not.
• New data structure called Hashing used to store and retrieve any
entry with constanttime O(1).
• This technique is irrelevant to size of the list and order.
• To increase the search efficiency the items to be stored in such a way
as to make it easy to find them later.
133. Hashing
- Hashing is a technique used to generate key where an element is to
be inserted or to be located from.
• Hash Table
- hash table is a data structure to store and retrieve data very fast.
- hash table consistof key and its value.
- Each location in the hash table is called cell or bucket.
- hash table is implemented using array.
- An element is accessed very fast if we know the key or its index.
Example- to store the Student record in hash table, Student rollno is used
as a key
134. Hash Function
- to map the key value into its corresponding index in hash table hash
function is used.
A hash function h transforms a key into an index in a hash table T[0…m-1]:
Where m is size of hash table.
-Use hash function to compute the index in the hash table for the given
key value.
-Hash function returns integer value which give the index value in the
hash table.
136. 1. Division method
h(key)= record%M
where M is size of the hash table
Example:
store following records in hash table 34, 20, 67, 8, 23.
M is 10
use hash function to map them in hash table
0 20
1
2
3 23
4 34
5
6
7 67
8 8
9
34%10= 4
20%10=0
67%10=7
8%10=8
23%10=3
137. Consider the following elements to be placed in the hash table of size 10,
37,90,45,22,17,49,55
0
1
2
3
4
5
6
7
8
9 49
37
45
90
22
H1(37)=37%10=7
H1(90)=90%10=0
H1(45)=45%10=5
H1(22)=22%10=2
H1(17)=17%10=7
H1(49)=49%10=9
H1(55)=55%10=5
In above example 17 and 55 are hashed to
same location this condition is called collision
138. 2. Mid square
- Square the key value and the middle or mid part of the result is used
as index.
- Example to place a record 3111 then
- Square of 3111= 9678321
- If the hash table size is 1000 then consider the middle 3 digits 783.
K 3205 7148
k2 10272025 51093904
H(k) 72 93
139. 3. Folding method
- Key value is divided into parts and add them
yields required hash address.
Key 3205 7148
H(key) 32+05=37 71+48=19
Note- the leading digit 1 in H(7148) is ignored.
140. Collision resolution techniques
• Two or more keys are mapping to same location in the hash table is
called collision.
Collision resolution techniques
• They are two broad ways of collision resolution techniques
1. Separate chaining: an array of linked list representation
2. Open addressing: array based implementation
(i) Linear probing (linear search)
(ii) Quadratic probing (nonlinear search)
(iii) Double hashing (uses two hash functions
141. Separate chaining
• Hash table is implemented as array of linked list.
• All the records which are mapped to same hash address are lined together to form a linked list.
• Example: Load the keys 23, 13, 21, 14, 7, 8, and 15 , in this order, in a hash table of size 7 using separate chaining with the hash function: h(key) = key % 7
h(23) = 23 % 7 = 2
h(13) = 13 % 7 = 6
h(21) = 21 % 7 = 0
h(14) = 14 % 7 = 0 collision
h(7) = 7 % 7 = 0 collision
h(8) = 8 % 7 = 1
h(15) = 15 % 7 = 1 collision
142. Linear probing (linear search)
• Idea is that when the collision occurs, find the next available slot in
the hash table (i.e probing)
• The process wraps around to the beginning of the table
• Example 89, 18, 49, 58, 9 and hash table size is 10
0 1 2 3 4 5 6 7 8 9
891849 58 9
89%10=9
18%10=8
49%10=9
58%10=8
9%10=9
143. 3. Quadratic probing
- It operates by taking hash value and adding successive values of an arbitrary
quadratic polynomial.
- Uses following formula
Hi(key)= (Hashvalue+i2)%m
Where,
m may be table size or any prime number
145. 4. Double hashing
- Second hash function is applied when a collision is occurred.
- the resultant of second hash function is to get the number of positions from the
point of collision to insert.
H1(key)= keyvalue%tablesize
H2(key)= M-(key % M)
Where,
M is prime number smaller than table size.