SlideShare a Scribd company logo
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
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
 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
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
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
Pop operation- delete element from the stack
S. Durga Devi ,CSE,CBIT
Example :-
S. Durga Devi ,CSE,CBIT
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
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
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
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
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
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
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
 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
 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
 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
 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
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
/* 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
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
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
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
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
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
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
Examples
Infix
Expression
Prefix
Expression
Postfix
Expression
2 + 3 + 2 3 2 3 +
2 + 3 * 5 + 2 * 3 5 2 3 5 * +
(2 + 3) * 5 * + 2 3 5 2 3 + 5 *
2 * 3 – (5 + 9)
– * 2 3 +
5 9
2 3 * 5 9 +
–
S. Durga Devi ,CSE,CBIT
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
Note
• the lower precedence operator never placed on
top of the higher precedence.
• (A-B)*(D/E)
S. Durga Devi ,CSE,CBIT
Operator Precedence
S. Durga Devi ,CSE,CBIT
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
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
Evaluate the expression
• Postfix:- 5,6,2,+,*,12,4,/,-
Symbol scanned stack content
5 5
6 5 6
2 5 6 2
+ 5 8
* 40
12 40 12
4 40 12 4
/ 40 3
- 40-3
37
S. Durga Devi ,CSE,CBIT
Convert infix to postfix expression
1. (A-B)*(D/E)
2. (A+B^D)/(E-F)+G
3. A*(B+D)/E-F*(G+H/K)
4. ((A+B)*D)^(E-F)
5. (A-B)/((D+E)*F)
6. ((A+B)/D)^((E-F)*G)
7. 12/(7-3)+2*(1+5)
8. 5+3^2-8/4*3+6
9. 6+2^3+9/3-4*5
10. 6+2^3^2-4*5
Evaluate the postfix expression
1. 5,3,+,2,*,6,9,7,-,/,-
2. 3,5,+,6,4,-,*,4,1,-,2,^,+
3. 3,1,+,2,^7,4,1,-,2,*,+,5.-
S. Durga Devi ,CSE,CBIT
#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
for(i=0,j=0;i<l;i++){
if((isalpha(in[i]))||(isdigit(in[i])))
post[j++]=in[i];
else
{
if(in[i]=='(')
push(in[i]);
else if(in[i]==')')
while((ch=pop())!='(')
post[j++]=ch;
else
{
while(priority(in[i])<=priority(str[top]))
post[j++]=pop();
push(in[i]);
}}}while(top!=-1)
post[j++]=pop();
post[j]='0';
printf("n equivalent infix to postfix
is:%s",post);
int priority (char c)
{
switch(c)
{
case'+':
case'-': return 1;
case'*':
case'/':
return 2;
case'$':return 3;
case '^':return 4;
}
return 0;
}
int push(char c)
{str[++top]=c;
}
pop()
{
return(str[top--]);
}
S. Durga Devi ,CSE,CBIT
 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
Bus Stop
Queue
Bus
Stop
front
rear
rear rear rear rear
S. Durga Devi ,CSE,CBIT
Bus Stop Queue
Bus
Stop
front
rear
rear rear
S. Durga Devi ,CSE,CBIT
Bus Stop Queue
Bus
Stop
front
rear
rear
S. Durga Devi ,CSE,CBIT
Bus Stop Queue
Bus
Stop
front
rear
rear
S. Durga Devi ,CSE,CBIT
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
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
• 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
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
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
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
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
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
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
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
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
EMPTY QUEUE
Circular queues
Q[0] Q[1] Q[2] Q[3] Q[N]
Delete element 5S. Durga Devi ,CSE,CBIT
rear
S. Durga Devi ,CSE,CBIT
• 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
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
• 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
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
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
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
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
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
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
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
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7
100 54 355 102 43 10 287 5
100
PASS-1
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7
100 54 355 102 43 10 287 5
100 54
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7
100 54 355 102 43 10 287 5
100 54 355
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7
100 54 355 102 43 10 287 5
100 54 355102
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7
100 54 355 102 43 10 287 5
100 54 355102 43
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7
100 54 355 102 43 10 287 5
100 54 355102 43
10
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7
100 54 355 102 43 10 287 5
100 54 355102 43
10
287
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 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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
0 1 2 3 4 5 6 7
100 10 102 43 54 355 5 287
0 1 2 3 4 5 6 7 8 9
100 10
0 1 2 3 4 5 6 7
100 10 102 43 54 355 5 287
0 1 2 3 4 5 6 7 8 9
100 10
102
0 1 2 3 4 5 6 7
100 10 102 43 54 355 5 287
0 1 2 3 4 5 6 7 8 9
100 10
102
43
0 1 2 3 4 5 6 7
100 10 102 43 54 355 5 287
0 1 2 3 4 5 6 7 8 9
100 10
102
43 54
0 1 2 3 4 5 6 7
100 10 102 43 54 355 5 287
0 1 2 3 4 5 6 7 8 9
100 10
102
43 54
355
0 1 2 3 4 5 6 7
100 10 102 43 54 355 5 287
0 1 2 3 4 5 6 7 8 9
100 10
102
43 54
355
05
0 1 2 3 4 5 6 7
100 10 102 43 54 355 5 287
0 1 2 3 4 5 6 7 8 9
100 10
102
43 54
355
05
287
0 1 2 3 4 5 6 7
100 10 102 43 54 355 5 287
0 1 2 3 4 5 6 7 8 9
100 10
102
43 54
355
05
287
0 1 2 3 4 5 6 7
100 102 05 10 43 54 355 287
PASS-2 completed
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
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
100
102
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
100
102
005
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
100
102
005
010
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
100
102
005
010
043
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
100
102
005
010
043
054
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
100
102
005
010
043
054
355
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
100
102
005
010
043
054
355287
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
100
102
005
010
043
054
355287
0 1 2 3 4 5 6 7
5 10 43 54 100 102 287 355
Exercise use Radix sort
12 58 37 64 52 36 99 63 18 9 20 88 47
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()*/
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()*/
example
1.encq(A)
2.encq(B)
3.encq(c )
4. Encq ( D )
5.Decq
6.encq(E)
7. Decq
8.encq( F)
9.Decq
10. Decq
11.Decq
12. Decq
Dictionaries
6
92
41 8
<
>
=
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()
Example
Operation Output Dictionary
insert(5,A) (5,A) (5,A)
insert(7,B) (7,B) (5,A),(7,B)
insert(2,C) (2,C) (5,A),(7,B),(2,C)
insert(8,D) (8,D) (5,A),(7,B),(2,C),(8,D)
insert(2,E) (2,E) (5,A),(7,B),(2,C),(8,D),(2,E)
find(7) (7,B) (5,A),(7,B),(2,C),(8,D),(2,E)
find(4) null (5,A),(7,B),(2,C),(8,D),(2,E)
find(2) (2,C) (5,A),(7,B),(2,C),(8,D),(2,E)
findAll(2) (2,C),(2,E) (5,A),(7,B),(2,C),(8,D),(2,E)
size() 5 (5,A),(7,B),(2,C),(8,D),(2,E)
remove(find(5)) (5,A) (7,B),(2,C),(8,D),(2,E)
find(5) null (7,B),(2,C),(8,D),(2,E)
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()
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}
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)
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.
Linearsequential Search
• linearsequentialsearch of a list/array begins
at the beginning of the list/array and
continues until the item is found or the entire
list/array has been searched
Example: Successful Linear Search
Example: Failed Linear Search
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;
}
/* 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...");
}
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);
}
Search Algorithms
-All the array elements must be visited if search fails.
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)
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).
/* 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");
}
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);
}
/* 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();
}
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()
Static Hashing
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.
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
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.
Types of hash functions
1. Division method
2. Mid square
3. Digit folding
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
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
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
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.
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
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
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
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
Ex- 37,99,55,22,11, 17,40,87
0 1 2 3 4 5 6 7 8 9
37%10=7
37
99%10=9
99
55%10=5
55
22%10=2
22
11%10=1
11
17%10=7 but already occupied
Consider i=0 then
(17+02)%10=7
(17+12)%10=8
17
40%10=0
40
87%10=7 occupied
(87+12)%10=8 occupied
(87+22)%10=1 occupied
(87+32)%10=6
87
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.
Ex- 37,90,45,22,17,49,55
0 1 2 3 4 5 6 7 8 9
H1(37)=37%10=7
37
H1(90)=90%10=0
90
H1(45)=45%10=5
45
H1(22)=22%10=2
17
H1(17)=17%10=7
H2(17)=7-(17%7)=4
Move 4 locationsfrom collision
H1(55)=55%10=5
H2(55)=7-(55%7)=1
Move one location from collision
H1(49)=49%10=9
495522
• https://www.codingbot.net/2013/02/radix-
sort-algorithm-and-c-code.html

More Related Content

What's hot

Stacks & Queues By Ms. Niti Arora
Stacks & Queues By Ms. Niti AroraStacks & Queues By Ms. Niti Arora
Stacks & Queues By Ms. Niti Arora
kulachihansraj
 
Queues
QueuesQueues
Stack
StackStack
Unit 2 linked list
Unit 2   linked listUnit 2   linked list
Unit 2 linked list
DrkhanchanaR
 
UNIT II LINEAR DATA STRUCTURES – STACKS, QUEUES
UNIT II 	LINEAR DATA STRUCTURES – STACKS, QUEUES	UNIT II 	LINEAR DATA STRUCTURES – STACKS, QUEUES
UNIT II LINEAR DATA STRUCTURES – STACKS, QUEUES
Kathirvel Ayyaswamy
 
Infix to Postfix Conversion Using Stack
Infix to Postfix Conversion Using StackInfix to Postfix Conversion Using Stack
Infix to Postfix Conversion Using Stack
Soumen Santra
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
Lovely Professional University
 
Queue
QueueQueue
stack & queue
stack & queuestack & queue
stack & queue
manju rani
 
Stacks
StacksStacks
Stacks
sweta dargad
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
Zidny Nafan
 
Queue data structure
Queue data structureQueue data structure
Queue data structure
anooppjoseph
 
Data structure Stack
Data structure StackData structure Stack
Data structure Stack
Praveen Vishwakarma
 
Queue in Data Structure
Queue in Data Structure Queue in Data Structure
Queue in Data Structure
Janki Shah
 
Bubble sort | Data structure |
Bubble sort | Data structure |Bubble sort | Data structure |
Bubble sort | Data structure |
MdSaiful14
 
Unit I-Data structures stack & Queue
Unit I-Data structures stack & QueueUnit I-Data structures stack & Queue
Unit I-Data structures stack & Queue
DrkhanchanaR
 
heap Sort Algorithm
heap  Sort Algorithmheap  Sort Algorithm
heap Sort Algorithm
Lemia Algmri
 
9 python data structure-2
9 python data structure-29 python data structure-2
9 python data structure-2
Prof. Dr. K. Adisesha
 
Infix postfixcoversion
Infix postfixcoversionInfix postfixcoversion
Infix postfixcoversion
Pdr Patnaik
 

What's hot (20)

Stacks & Queues By Ms. Niti Arora
Stacks & Queues By Ms. Niti AroraStacks & Queues By Ms. Niti Arora
Stacks & Queues By Ms. Niti Arora
 
Queues
QueuesQueues
Queues
 
Stack
StackStack
Stack
 
Stack
StackStack
Stack
 
Unit 2 linked list
Unit 2   linked listUnit 2   linked list
Unit 2 linked list
 
UNIT II LINEAR DATA STRUCTURES – STACKS, QUEUES
UNIT II 	LINEAR DATA STRUCTURES – STACKS, QUEUES	UNIT II 	LINEAR DATA STRUCTURES – STACKS, QUEUES
UNIT II LINEAR DATA STRUCTURES – STACKS, QUEUES
 
Infix to Postfix Conversion Using Stack
Infix to Postfix Conversion Using StackInfix to Postfix Conversion Using Stack
Infix to Postfix Conversion Using Stack
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
 
Queue
QueueQueue
Queue
 
stack & queue
stack & queuestack & queue
stack & queue
 
Stacks
StacksStacks
Stacks
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
 
Queue data structure
Queue data structureQueue data structure
Queue data structure
 
Data structure Stack
Data structure StackData structure Stack
Data structure Stack
 
Queue in Data Structure
Queue in Data Structure Queue in Data Structure
Queue in Data Structure
 
Bubble sort | Data structure |
Bubble sort | Data structure |Bubble sort | Data structure |
Bubble sort | Data structure |
 
Unit I-Data structures stack & Queue
Unit I-Data structures stack & QueueUnit I-Data structures stack & Queue
Unit I-Data structures stack & Queue
 
heap Sort Algorithm
heap  Sort Algorithmheap  Sort Algorithm
heap Sort Algorithm
 
9 python data structure-2
9 python data structure-29 python data structure-2
9 python data structure-2
 
Infix postfixcoversion
Infix postfixcoversionInfix postfixcoversion
Infix postfixcoversion
 

Similar to stacks and queues

Stack and its operations, Queue and its operations
Stack and its operations, Queue and its operationsStack and its operations, Queue and its operations
Stack and its operations, Queue and its operations
poongothai11
 
Stacks in c++
Stacks in c++Stacks in c++
Stacks in c++
Vineeta Garg
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manual
nikshaikh786
 
Lec5-Stack-bukc-28022024-112316am (1) .pptx
Lec5-Stack-bukc-28022024-112316am (1) .pptxLec5-Stack-bukc-28022024-112316am (1) .pptx
Lec5-Stack-bukc-28022024-112316am (1) .pptx
haaamin01
 
Data structure and algorithm.(dsa)
Data structure and algorithm.(dsa)Data structure and algorithm.(dsa)
Data structure and algorithm.(dsa)
mailmerk
 
Stacks,queues,linked-list
Stacks,queues,linked-listStacks,queues,linked-list
Stacks,queues,linked-list
pinakspatel
 
Data structures stacks
Data structures   stacksData structures   stacks
Data structures stacks
maamir farooq
 
Stacks
StacksStacks
Stacks
Sadaf Ismail
 
Stack - Data Structure - Notes
Stack - Data Structure - NotesStack - Data Structure - Notes
Stack - Data Structure - Notes
Omprakash Chauhan
 
Unit 3 stack
Unit 3   stackUnit 3   stack
Unit 3 stack
kalyanineve
 
What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
What is Stack, Its Operations, Queue, Circular Queue, Priority QueueWhat is Stack, Its Operations, Queue, Circular Queue, Priority Queue
What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
Balwant Gorad
 
03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays03 stacks and_queues_using_arrays
03 stacks and_queues_using_arraystameemyousaf
 
Stack and its applications
Stack and its applicationsStack and its applications
Stack and its applications
Ahsan Mansiv
 
Chap 4 List of Data Structure.ppt
Chap 4 List of Data Structure.pptChap 4 List of Data Structure.ppt
Chap 4 List of Data Structure.ppt
shashankbhadouria4
 
DS MOD2 (1) (1).pptx
DS MOD2 (1) (1).pptxDS MOD2 (1) (1).pptx
DS MOD2 (1) (1).pptx
kumarkaushal17
 
04 stacks
04 stacks04 stacks
04 stacks
Rajan Gautam
 
Data Structures and Agorithm: DS 06 Stack.pptx
Data Structures and Agorithm: DS 06 Stack.pptxData Structures and Agorithm: DS 06 Stack.pptx
Data Structures and Agorithm: DS 06 Stack.pptx
RashidFaridChishti
 
Stack linked list
Stack linked listStack linked list
Stack linked listbhargav0077
 
Data Structures by Maneesh Boddu
Data Structures by Maneesh BodduData Structures by Maneesh Boddu
Data Structures by Maneesh Boddu
maneesh boddu
 
Unit i(dsc++)
Unit i(dsc++)Unit i(dsc++)
Unit i(dsc++)
Durga Devi
 

Similar to stacks and queues (20)

Stack and its operations, Queue and its operations
Stack and its operations, Queue and its operationsStack and its operations, Queue and its operations
Stack and its operations, Queue and its operations
 
Stacks in c++
Stacks in c++Stacks in c++
Stacks in c++
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manual
 
Lec5-Stack-bukc-28022024-112316am (1) .pptx
Lec5-Stack-bukc-28022024-112316am (1) .pptxLec5-Stack-bukc-28022024-112316am (1) .pptx
Lec5-Stack-bukc-28022024-112316am (1) .pptx
 
Data structure and algorithm.(dsa)
Data structure and algorithm.(dsa)Data structure and algorithm.(dsa)
Data structure and algorithm.(dsa)
 
Stacks,queues,linked-list
Stacks,queues,linked-listStacks,queues,linked-list
Stacks,queues,linked-list
 
Data structures stacks
Data structures   stacksData structures   stacks
Data structures stacks
 
Stacks
StacksStacks
Stacks
 
Stack - Data Structure - Notes
Stack - Data Structure - NotesStack - Data Structure - Notes
Stack - Data Structure - Notes
 
Unit 3 stack
Unit 3   stackUnit 3   stack
Unit 3 stack
 
What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
What is Stack, Its Operations, Queue, Circular Queue, Priority QueueWhat is Stack, Its Operations, Queue, Circular Queue, Priority Queue
What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
 
03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays
 
Stack and its applications
Stack and its applicationsStack and its applications
Stack and its applications
 
Chap 4 List of Data Structure.ppt
Chap 4 List of Data Structure.pptChap 4 List of Data Structure.ppt
Chap 4 List of Data Structure.ppt
 
DS MOD2 (1) (1).pptx
DS MOD2 (1) (1).pptxDS MOD2 (1) (1).pptx
DS MOD2 (1) (1).pptx
 
04 stacks
04 stacks04 stacks
04 stacks
 
Data Structures and Agorithm: DS 06 Stack.pptx
Data Structures and Agorithm: DS 06 Stack.pptxData Structures and Agorithm: DS 06 Stack.pptx
Data Structures and Agorithm: DS 06 Stack.pptx
 
Stack linked list
Stack linked listStack linked list
Stack linked list
 
Data Structures by Maneesh Boddu
Data Structures by Maneesh BodduData Structures by Maneesh Boddu
Data Structures by Maneesh Boddu
 
Unit i(dsc++)
Unit i(dsc++)Unit i(dsc++)
Unit i(dsc++)
 

Recently uploaded

Vaccine management system project report documentation..pdf
Vaccine management system project report documentation..pdfVaccine management system project report documentation..pdf
Vaccine management system project report documentation..pdf
Kamal Acharya
 
Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.
PrashantGoswami42
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
SamSarthak3
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
R&R Consult
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
TECHNICAL TRAINING MANUAL GENERAL FAMILIARIZATION COURSE
TECHNICAL TRAINING MANUAL   GENERAL FAMILIARIZATION COURSETECHNICAL TRAINING MANUAL   GENERAL FAMILIARIZATION COURSE
TECHNICAL TRAINING MANUAL GENERAL FAMILIARIZATION COURSE
DuvanRamosGarzon1
 
Democratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek AryaDemocratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek Arya
abh.arya
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
MdTanvirMahtab2
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
Kamal Acharya
 
addressing modes in computer architecture
addressing modes  in computer architectureaddressing modes  in computer architecture
addressing modes in computer architecture
ShahidSultan24
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation & Control
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
ankuprajapati0525
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
AafreenAbuthahir2
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
seandesed
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Dr.Costas Sachpazis
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
Pratik Pawar
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
Intella Parts
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
Robbie Edward Sayers
 

Recently uploaded (20)

Vaccine management system project report documentation..pdf
Vaccine management system project report documentation..pdfVaccine management system project report documentation..pdf
Vaccine management system project report documentation..pdf
 
Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
TECHNICAL TRAINING MANUAL GENERAL FAMILIARIZATION COURSE
TECHNICAL TRAINING MANUAL   GENERAL FAMILIARIZATION COURSETECHNICAL TRAINING MANUAL   GENERAL FAMILIARIZATION COURSE
TECHNICAL TRAINING MANUAL GENERAL FAMILIARIZATION COURSE
 
Democratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek AryaDemocratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek Arya
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
 
addressing modes in computer architecture
addressing modes  in computer architectureaddressing modes  in computer architecture
addressing modes in computer architecture
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
 

stacks and queues

  • 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
  • 6. Pop operation- delete element from the stack S. Durga Devi ,CSE,CBIT
  • 7. Example :- 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
  • 27. Examples Infix Expression Prefix Expression Postfix Expression 2 + 3 + 2 3 2 3 + 2 + 3 * 5 + 2 * 3 5 2 3 5 * + (2 + 3) * 5 * + 2 3 5 2 3 + 5 * 2 * 3 – (5 + 9) – * 2 3 + 5 9 2 3 * 5 9 + – 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
  • 33. Evaluate the expression • Postfix:- 5,6,2,+,*,12,4,/,- Symbol scanned stack content 5 5 6 5 6 2 5 6 2 + 5 8 * 40 12 40 12 4 40 12 4 / 40 3 - 40-3 37 S. Durga Devi ,CSE,CBIT
  • 34. Convert infix to postfix expression 1. (A-B)*(D/E) 2. (A+B^D)/(E-F)+G 3. A*(B+D)/E-F*(G+H/K) 4. ((A+B)*D)^(E-F) 5. (A-B)/((D+E)*F) 6. ((A+B)/D)^((E-F)*G) 7. 12/(7-3)+2*(1+5) 8. 5+3^2-8/4*3+6 9. 6+2^3+9/3-4*5 10. 6+2^3^2-4*5 Evaluate the postfix expression 1. 5,3,+,2,*,6,9,7,-,/,- 2. 3,5,+,6,4,-,*,4,1,-,2,^,+ 3. 3,1,+,2,^7,4,1,-,2,*,+,5.- 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
  • 36. for(i=0,j=0;i<l;i++){ if((isalpha(in[i]))||(isdigit(in[i]))) post[j++]=in[i]; else { if(in[i]=='(') push(in[i]); else if(in[i]==')') while((ch=pop())!='(') post[j++]=ch; else { while(priority(in[i])<=priority(str[top])) post[j++]=pop(); push(in[i]); }}}while(top!=-1) post[j++]=pop(); post[j]='0'; printf("n equivalent infix to postfix is:%s",post); int priority (char c) { switch(c) { case'+': case'-': return 1; case'*': case'/': return 2; case'$':return 3; case '^':return 4; } return 0; } int push(char c) {str[++top]=c; } pop() { return(str[top--]); } 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
  • 38. Bus Stop Queue Bus Stop front rear rear rear rear rear S. Durga Devi ,CSE,CBIT
  • 39. Bus Stop Queue Bus Stop front rear rear 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
  • 53. EMPTY QUEUE Circular queues Q[0] Q[1] Q[2] Q[3] Q[N] Delete element 5S. Durga Devi ,CSE,CBIT
  • 54. rear 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
  • 65. 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 100 54 355 102 43 10 287 5 100 PASS-1
  • 66. 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 100 54 355 102 43 10 287 5 100 54
  • 67. 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 100 54 355 102 43 10 287 5 100 54 355
  • 68. 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 100 54 355 102 43 10 287 5 100 54 355102
  • 69. 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 100 54 355 102 43 10 287 5 100 54 355102 43
  • 70. 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 100 54 355 102 43 10 287 5 100 54 355102 43 10
  • 71. 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 100 54 355 102 43 10 287 5 100 54 355102 43 10 287
  • 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
  • 89. 0 1 2 3 4 5 6 7 100 10 102 43 54 355 5 287 0 1 2 3 4 5 6 7 8 9 100 10
  • 90. 0 1 2 3 4 5 6 7 100 10 102 43 54 355 5 287 0 1 2 3 4 5 6 7 8 9 100 10 102
  • 91. 0 1 2 3 4 5 6 7 100 10 102 43 54 355 5 287 0 1 2 3 4 5 6 7 8 9 100 10 102 43
  • 92. 0 1 2 3 4 5 6 7 100 10 102 43 54 355 5 287 0 1 2 3 4 5 6 7 8 9 100 10 102 43 54
  • 93. 0 1 2 3 4 5 6 7 100 10 102 43 54 355 5 287 0 1 2 3 4 5 6 7 8 9 100 10 102 43 54 355
  • 94. 0 1 2 3 4 5 6 7 100 10 102 43 54 355 5 287 0 1 2 3 4 5 6 7 8 9 100 10 102 43 54 355 05
  • 95. 0 1 2 3 4 5 6 7 100 10 102 43 54 355 5 287 0 1 2 3 4 5 6 7 8 9 100 10 102 43 54 355 05 287
  • 96. 0 1 2 3 4 5 6 7 100 10 102 43 54 355 5 287 0 1 2 3 4 5 6 7 8 9 100 10 102 43 54 355 05 287 0 1 2 3 4 5 6 7 100 102 05 10 43 54 355 287 PASS-2 completed
  • 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
  • 98. 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 100 102
  • 99. 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 100 102 005
  • 100. 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 100 102 005 010
  • 101. 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 100 102 005 010 043
  • 102. 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 100 102 005 010 043 054
  • 103. 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 100 102 005 010 043 054 355
  • 104. 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 100 102 005 010 043 054 355287
  • 105. 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 100 102 005 010 043 054 355287 0 1 2 3 4 5 6 7 5 10 43 54 100 102 287 355
  • 106. Exercise use Radix sort 12 58 37 64 52 36 99 63 18 9 20 88 47
  • 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()*/
  • 109. example 1.encq(A) 2.encq(B) 3.encq(c ) 4. Encq ( D ) 5.Decq 6.encq(E) 7. Decq 8.encq( F) 9.Decq 10. Decq 11.Decq 12. Decq
  • 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()
  • 112. Example Operation Output Dictionary insert(5,A) (5,A) (5,A) insert(7,B) (7,B) (5,A),(7,B) insert(2,C) (2,C) (5,A),(7,B),(2,C) insert(8,D) (8,D) (5,A),(7,B),(2,C),(8,D) insert(2,E) (2,E) (5,A),(7,B),(2,C),(8,D),(2,E) find(7) (7,B) (5,A),(7,B),(2,C),(8,D),(2,E) find(4) null (5,A),(7,B),(2,C),(8,D),(2,E) find(2) (2,C) (5,A),(7,B),(2,C),(8,D),(2,E) findAll(2) (2,C),(2,E) (5,A),(7,B),(2,C),(8,D),(2,E) size() 5 (5,A),(7,B),(2,C),(8,D),(2,E) remove(find(5)) (5,A) (7,B),(2,C),(8,D),(2,E) find(5) null (7,B),(2,C),(8,D),(2,E)
  • 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.
  • 117. Linearsequential Search • linearsequentialsearch of a list/array begins at the beginning of the list/array and continues until the item is found or the entire list/array has been searched
  • 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); }
  • 123. Search Algorithms -All the array elements must be visited if search fails.
  • 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.
  • 135. Types of hash functions 1. Division method 2. Mid square 3. Digit folding
  • 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
  • 144. Ex- 37,99,55,22,11, 17,40,87 0 1 2 3 4 5 6 7 8 9 37%10=7 37 99%10=9 99 55%10=5 55 22%10=2 22 11%10=1 11 17%10=7 but already occupied Consider i=0 then (17+02)%10=7 (17+12)%10=8 17 40%10=0 40 87%10=7 occupied (87+12)%10=8 occupied (87+22)%10=1 occupied (87+32)%10=6 87
  • 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.
  • 146. Ex- 37,90,45,22,17,49,55 0 1 2 3 4 5 6 7 8 9 H1(37)=37%10=7 37 H1(90)=90%10=0 90 H1(45)=45%10=5 45 H1(22)=22%10=2 17 H1(17)=17%10=7 H2(17)=7-(17%7)=4 Move 4 locationsfrom collision H1(55)=55%10=5 H2(55)=7-(55%7)=1 Move one location from collision H1(49)=49%10=9 495522