Sei sulla pagina 1di 132

CSE2003 - Data Structures and

Algorithms
Outline
• Importance of the course
• About the course content
• Student Projects
• Conclusion
Importance of the course
• Any domain has problems that require algorithmic solution
• We need to be able to provide solutions to problems
• Find the best solution from a wide range of choices
• Learn methods to develop solutions

Problem ->Idea ->Solution ->Algorithm->Pseudocode ->code


->Compiled program
Importance of the course
• In computer science, data structures and algorithms may be
the most fundamental among other subfields of it.
What is data structure?
• Data structure is a particular way of storing and
organizing information in a computer so that it can be
retrieved and used most productively.
• Example:
– A librarian organizes the books(data) into a particular form
(data structure) to efficiently perform a task(find a book on
data structure).
Important Data Structures

Queue Stack Tree Graph


Importance of Data Structure
• Different kinds of data structures are suited for different
computer applications and tasks.
– Use of appropriate data structure enables a computer system to
perform its task more efficiently, by influencing the ability of
computer to store and retrieve data from any location in its
memory.
• For systems to be economical the data must be organized
(into data structures) in such a way as to support efficient
manipulation (by algorithms).
What is an Algorithm?
• An algorithm is a sequence of unambiguous
instructions for solving a problem, i.e., for
obtaining a required output for any legitimate
input in a finite amount of time.

• An input to an algorithm specifies an instance of


the problem the algorithm solves.
Importance of Algorithms
• General approaches to the construction
of efficient solutions to problems.
– Provide templates suited to solving a broad range
of diverse problems.
– Can be translated into common control and data
structures provided by most high-level languages.
– The temporal and spatial requirements of the
algorithms which result can be precisely analysed.
Importance of the course
• Data Structures and algorithms are important
for Job Interviews.
Course Objectives
• To stress the importance of Algorithms and Data structures in
becoming a more productive computer scientist.
• To appreciate and understand the Algorithms and Data
structures used for solving a problem are much more
important than knowing the exact code for it in some
programming language.
• To provide an insight into the intrinsic nature of the problem
as well as possible solution techniques, independent of
programming language, programming paradigms, computer
hardware or any other implementation technique.
Learning Outcome (LO)
• Design an efficient algorithm for a problem using a specified
paradigm along with a proper data structure .
• Choose an appropriate design paradigm that solves the given
problem efficiently along with appropriate data structures.
• Map real-world problems to algorithmic solutions.
• Analyze algorithms asymptotically and compute the
performance analysis of algorithms with the same
functionality.
• Identify the existence of problems which defy algorithmic
solution.
• Recognize a few problems which defy efficient algorithmic
solution.
Student Projects
• Goals
– To improve analytical reasoning and programming
skills
– To distinguish which data structure to be used in
practical problem
Student Projects
• Project Evaluation
– Based on Four reviews
• Students should find a solution within the
stipulated time
– More points for novel concept
Student Projects
• Identification of the data structure in the practical problem
• Students may combine two data structures to solve the
problem
• Build a new data structure which is combination of data
structures covered by the material
• Implement it in a different way
Algorithm design and Analysis process
Algorithm design technique
• An algorithm design technique (or “strategy”
or “paradigm”) is a general approach to
solving problems algorithmically that is
applicable to a variety of problems from
different areas of computing.
Algorithm design techniques
• Brute force
• Greedy
• Divide and Conquer
• Dynamic programming
• Backtracking
Text Books & Reference Bookss
Text Books
• 1. Thomas H. Cormen, C.E. Leiserson, R L.Rivest and C. Stein, Introduction to
Algorithms , Paper Back 2010, Third edition, MIT Press, 2010
Reference Books
• 1. Sanjoy Dasgupta, C.Papadimitriou and U.Vazirani , Algorithms , Tata McGraw-
Hill, 2006.
• 2. A. V. Aho, J.E. Hopcroft and J. D. Ullman, Data Strucures and Algorithms ,Pearson
India, Ist Edition, 2002.
• 3. A. V. Aho, J.E. Hopcroft and J. D. Ullman, Design and Analysis of Computer
Algorithms ,Pearson,1st edition, 2011.
• 4. Sara Baase , Allen Van Gelder, Computer Algorithms, Introduction to Design and
Analysis, 3rd edition, Wesley Longman Publishing, 2000.
• 5. Mark Allen Weiss, Data Structures and Algorithm Analysis in C, 2nd edition,
Pearson Education, 2007
Other Information
• Video Lectures on “Introduction to algorithms” @ MIT
– http://ocw.mit.edu/courses/electrical-engineering-and-computer-
science/6-046j-introduction-to-algorithms-sma-5503-fall-2005/video-
lectures/

• Coursera: Algorithms: Design and Analysis (part -1 and part -2)


– https://www.coursera.org/course/algo
– https://www.coursera.org/course/algo2
Introduction to the Stack ADT

• A stack is a data structure that stores and


retrieves items in a last-in-first-out (LIFO)
manner.
Applications of Stacks
• Computer systems use stacks during a
program’s execution to store function return
addresses, local variables, etc.
• Some calculators use stacks for performing
mathematical operations.
Uses of Stacks in Computing
Useful for any kind of problem involving LIFO
data

• Backtracking: in puzzles and games


• Browsers
– To keep track of pages visited in a browser tab

3-23
Uses of Stacks in Computing
• Word Processors, editors
– To check expressions or strings of text for matching
parentheses / brackets
e.g. if (a == b)
{ c = (d + e) * f;
}
– To implement undo operations
• Keeps track of the most recent operations
• Markup languages (e.g. HTML, XML): have
formatting information (tags) as well as raw text
– To check for matching tags
e.g. <HEAD>
<TITLE>Computer Science 1027a</TITLE>
</HEAD>
3-24
Uses of Stacks in Computing
• Stack Calculators
– To convert an infix expression to postfix, to
make evaluation easier (more on this later)
Infix expression: a*b+c
Postfix expression: a b * c +
– To evaluate postfix expressions (ditto)
• Compilers
– To convert infix expressions to postfix, to make
translation of a high-level language such as
Java or C to a lower level language easier

3-25
Uses of Stacks in Computing
• Call stack (Runtime stack)
– Used by runtime system when methods are
invoked, for method call / return processing (more
on this later)
• e.g. main calls method1
method1 calls method 2
method 2 returns …
– Holds “call frame” containing local variables,
parameters, etc.
– Why is a stack structure used for this?

3-26
Stack Specification
• Definitions: (provided by the user)
– MAX_ITEMS: Max number of items that might be on
the stack
– ItemType: Data type of the items on the stack
• Operations
– MakeEmpty
– Boolean IsEmpty
– Boolean IsFull
– Push (ItemType newItem)
– Pop (ItemType& item)
Push (ItemType newItem)
• Function: Adds newItem to the top of the
stack.
• Preconditions: Stack has been initialized
and is not full.
• Postconditions: newItem is at the top of
the stack.
Pop (ItemType& item)
• Function: Removes topItem from stack and
returns it in item.
• Preconditions: Stack has been initialized and is
not empty.
• Postconditions: Top element has been
removed from stack and item is a copy of the
removed element.
Stack Implementation
#include "ItemType.h"
// Must be provided by the user of the class
// Contains definitions for MAX_ITEMS and ItemType
class StackType {
public:
StackType();
void MakeEmpty();
bool IsEmpty() const;
bool IsFull() const;
void Push(ItemType);
void Pop(ItemType&);
private:
int top;
ItemType items[MAX_ITEMS];
};
Stack Implementation (cont.)
StackType::StackType()
{
top = -1;
}
void StackType::MakeEmpty()
{
top = -1;
}
bool StackType::IsEmpty() const
{
return (top == -1);
}
Stack Implementation (cont.)
bool StackType::IsFull() const
{
return (top == MAX_ITEMS-1);
}

void StackType::Push(ItemType newItem)


{
top++;
items[top] = newItem;
}

void StackType::Pop(ItemType& item)


{
item = items[top];
top--;
}
Stack overflow
• The condition resulting from trying to push
an element onto a full stack.
if(!stack.IsFull())
stack.Push(item);
Stack underflow
• The condition resulting from trying to pop
an empty stack.
if(!stack.IsEmpty())
stack.Pop(item);
The Towers of Hanoi
A Stack-based Application-1

– GIVEN: three poles


– a set of discs on the first pole, discs of different sizes, the smallest
discs at the top
– GOAL: move all the discs from the left pole to the right one.
– CONDITIONS: only one disc may be moved at a time.
– A disc can be placed either on an empty pole or on top of a larger
disc.
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi – Recursive Solution
void hanoi (int discs,
Stack fromPole,
Stack toPole,
Stack aux) {
Disc d;
if( discs >= 1) {
hanoi(discs-1, fromPole, aux, toPole);
d = fromPole.pop();
toPole.push(d);
hanoi(discs-1,aux, toPole, fromPole);
}
Stack Application-2
• Converting Decimal to Binary: Consider the following pseudocode
1) Read (number)
2) Loop (number > 0)
1) digit = number modulo 2
2) print (digit)
3) number = number / 2

The problem with this code is that it will print the binary
number backwards. (ex: 19 becomes 11001000 instead of 00010011. )
To remedy this problem, instead of printing the digit right away, we can
push it onto the stack. Then after the number is done being converted, we
pop the digit out of the stack and print it.
Infix, Postfix and Prefix Expressions
Stack application-3
• INFIX: From our schools times we have been familiar with the
expressions in which operands surround the operator, e.g.
x+y, 6*3 etc this way of writing the Expressions is called infix
notation.

• POSTFIX: Postfix notation are also Known as Reverse Polish


Notation (RPN). They are different from the infix and prefix
notations in the sense that in the postfix notation, operator
comes after the operands, e.g. xy+, xyz+* etc.

• PREFIX: Prefix notation also Known as Polish notation.In the


prefix notation, as the name only suggests, operator comes
before the operands, e.g. +xy, *+xyz etc.
WHY
• Why to use these weird looking PREFIX and POSTFIX notations
when we have simple INFIX notation?

• To our surprise INFIX notations are not as simple as they seem


specially while evaluating them. To evaluate an infix
expression we need to consider Operators’ Priority and
Associative property
– For example expression 3+5*4 evaluate to 32 i.e. (3+5)*4
or to 23 i.e. 3+(5*4).

• To solve this problem Precedence or Priority of the operators


were defined. Operator precedence governs evaluation order.
An operator with higher precedence is applied before an
operator with lower precedence.
Infix Expression Is Hard To Parse
• Need operator priorities, tie breaker, and
delimiters.
• This makes computer evaluation more
difficult than is necessary.
• Postfix and prefix expression forms do not
rely on operator priorities, a tie breaker,
or delimiters.
• So it is easier to evaluate expressions that
are in these forms.
• Due to above mentioned problem of considering operators' Priority
and Associative property while evaluating an expression using infix
notation, we use prefix and postfix notations.

• Both prefix and postfix notations have an advantage over infix that
while evaluating an expression in prefix or postfix form we need not
consider the Priority and Associative property (order of brackets).
– E.g. x/y*z becomes */xyz in prefix and xy/z* in postfix.
Both prefix and postfix notations make Expression
Evaluation a lot easier.
Examples of infix to prefix and post fix
Infix PostFix Prefix

A+B AB+ +AB

(A+B) * (C + D) AB+CD+* *+AB+CD


Algorithm for Infix to Postfix
1) Examine the next element in the input.
2) If it is operand, output it.
3) If it is opening parenthesis, push it on stack.
4) If it is an operator, then
i) If stack is empty, push operator on stack.
ii) If the top of stack is opening parenthesis, push operator on stack
iii) If it has higher priority than the top of stack, push operator on stack.
iv) Else pop the operator from the stack and output it, repeat step 4

5) If it is a closing parenthesis, pop operators from stack and output them


until an opening parenthesis is encountered. pop and discard the opening
parenthesis.
6) If there is more input go to step 1
7) If there is no more input, pop the remaining operators to output.
A summary of the rules follows:

1. Print operands as they arrive.


2. If the stack is empty or contains a left parenthesis on top, push the
incoming operator onto the stack.
3. If the incoming symbol is a left parenthesis, push it on the stack.
4. If the incoming symbol is a right parenthesis, pop the stack and print the
operators until you see a left parenthesis. Discard the pair of parentheses.
5. If the incoming symbol has higher precedence than the top of the stack,
push it on the stack.
6. If the incoming symbol has equal precedence with the top of the stack,
pop and print the top of the stack and then push the incoming operator
7. If the incoming symbol has lower precedence than the symbol on the top
of the stack, pop the stack and print the top operator. Then test the
incoming operator against the new top of stack.
8. At the end of the expression, pop and print all operators on the stack. (No
parentheses should remain.)
Suppose we want to convert 2*3/(2-1)+5*3 into Postfix form,
Expression Stack Output
2 Empty 2
* * 2
3 * 23
/ / 23*
( /( 23*
2 /( 23*2
- /(- 23*2
1 /(- 23*21
) / 23*21-
+ + 23*21-/
5 + 23*21-/5
* +* 23*21-/53
3 +* 23*21-/53
Empty 23*21-/53*+
So, the Postfix Expression is 23*21-/53*+
Evaluate postfix expressions
stack application-4
• Postfix notation is another way of writing arithmetic
expressions.
• In postfix notation, the operator is written after the
two operands.
infix: 2+5 postfix: 2 5 +
• Expressions are evaluated from left to right.

• Precedence rules and parentheses are never


needed!!
– The algorithm: Use a stack
• When you see operands, push them.
• When you see an operator, pop the last
two operands, apply the operator, and
push the result onto the stack.
• When you're done, the one remaining
stack element is the result.
Example: postfix expressions
(cont.)
Postfix expressions:
Algorithm using stacks (cont.)
Postfix expressions:
Algorithm using stacks

WHILE more input items exist


Get an item
IF item is an operand
stack.Push(item)
ELSE
stack.Pop(operand2)
stack.Pop(operand1)
Compute result
stack.Push(result)
stack.Pop(result)
Exercise 1:

Write a function that replaces each copy of an item in a


stack with another item. Use the following specification.
ReplaceItem(StackType& stack, ItemType oldItem,
ItemType newItem)
Function: Replaces all occurrences of oldItem with
newItem.
Precondition: stack has been initialized.
Postconditions: Each occurrence of oldItem in stack has
been replaced by newItem.
Stack tempStack
{
ItemType item;
StackType tempStack;

while (!Stack.IsEmpty()) { 3 1
Stack.Pop(item);
if (item==oldItem) 2 5
tempStack.Push(newItem); 1 3
else Stack
tempStack.Push(item);
}
while (!tempStack.IsEmpty()) {
tempStack.Pop(item);
Stack.Push(item); 3
}
}
oldItem = 2 5
newItem = 5 1
Exercise 2:
Parentheses Matching using stacks
• Each “(”, “{”, or “[” must be paired with a
matching “)”, “}”, or “[”
– correct: ( )(( )){([( )])}
– correct: ((( )(( )){([( )])}
– incorrect: )(( )){([( )])}
– incorrect: ({[ ])}
– incorrect: (

Stacks 60
Parentheses Matching Algorithm
Algorithm ParenMatch(X,n):
Input: An array X of n tokens, each of which is either a grouping symbol, a
variable, an arithmetic operator, or a number
Output: true if and only if all the grouping symbols in X match
Let S be an empty stack
for i=0 to n-1 do
if X[i] is an opening grouping symbol then
S.push(X[i])
else if X[i] is a closing grouping symbol then
if S.isEmpty() then
return false {nothing to match with}
if S.pop() does not match the type of X[i] then
return false {wrong type}
if S.isEmpty() then
return true {every symbol matched}
else
return false {some symbols were never matched}

Stacks 61
Exercise 3:
• Consider an input file of exam scores in
reverse ABC order:
Yeilding Janet 87
White Steven 84
Todd Kim 52
Tashev Sylvia 95
...

• Write code to print the exam scores in ABC


order using a stack.
Exercise 4:
• Pavithra is browsing about the competition
“Big Business Idea” in NDTV PROFIT .She has
noted down all the topics and criteria about
the competition. She forgot to note down
deadline. She has pressed back button in her
browser window to get back to the previously
visited page. Help Pavithra by using
appropriate data structure.
Problem Analysis
Input
 HTML page Menu heading (Home , Venue,
Schedule, Rules to participants)
Output
 Displays page name in the order of visit
(it may change every time)
Data structure:
Need a data structure which will helps us to
traverse back to the recently visited page link
How we are going to proceed….
• Step1: Get the html link from the user in the
order of visiting the web pages
• Step2: Store it (Technically PUSH it) in STACK
data structure using ADT operations
• step3:Retrive the recently visited page link
using POP ADT operation
• Step 4:Check for the condition stack “is
empty” or “isfull” before PUSH and POP
respectively.
Static and Dynamic Stacks
• Static Stacks
– Fixed size
– Can be implemented with an array
• Dynamic Stacks
– Grow in size as needed
– Can be implemented with a linked list
Dynamic Stacks
• A dynamic stack is built on a linked list instead of an
array.
• A linked list-based stack offers two advantages over
an array-based stack.
– No need to specify the starting size of the stack. A dynamic
stack simply starts as an empty linked list, and then
expands by one node each time a value is pushed.
– A dynamic stack will never be full, as long as the system
has enough free memory.
STACK USING LINKED LIST
• We will create a linked list and insert an element ‘10’ and address as ‘0’.using top for the
first node.
• For second node insert data element ‘20’ and insert first node address at second node
address field.
• For third node insert data element ‘30’ and insert second node address at third node
address field . after thirty we will stop the process .
• If we want to print the elements 30,20,10 will be displayed, This follows LIFO concept.
Stack using linked list
• Inserting 100, top

TOP
100 NULL

100x3
Stack using linked list
• Inserting 300

Address
TOP 100x3
300
200x3
100 NULL
100x3
Stack using linked list
• Inserting 500

TOP
500 200x3
300x3
300 100x3
200x3

100 Null

100x3
Stack using linked list-Poping
• Pop- will delete 500

TOP 100x3
300
200d3

100 Null
Stack using linked list
• Pop- will delete 300

TOP
100 Null

100x3
Stack using linked list
• Pop- will delete 100

TOP
NULL
Introduction to the Queue ADT
• Like stack, a queue (pronounced "cue") is a data
structure that holds a sequence of elements.

• A queue, however, provides access to its elements in


first-in, first-out (FIFO) order.

• The elements in a queue are processed like


customers standing in a grocery check-out line: the
first customer in line is the first one served.
DEFINITION OF QUEUE
• A Queue is an ordered collection of items from which items may be
deleted at one end (called the front of the queue) and into which
items may be inserted at the other end (the rear of the queue).
• The first element inserted into the queue is the first element to be
removed. For this reason a queue is sometimes called a fifo (first-in
first-out) list as opposed to the stack, which is a lifo (last-in first-out).
Example Applications of Queues
• In a multi-user system, a queue is used to hold print
jobs submitted by users , while the printer services
those jobs one at a time.
• Communications software also uses queues to hold
information received over networks and dial-up
connections.
• Sometimes information is transmitted to a system
faster than it can be processed, so it is placed in a
queue when it is received.
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)
Implementation of Queue
• Array based implementation

• Linked list implementation


Static and Dynamic Queues
• Just as stacks, queues are implemented using
arrays or linked lists.
• Dynamic queues offer the same advantages
over static queues that dynamic stacks offer
over static stacks.
Queue Operations
• The two primary queue operations are
enqueuing and dequeuing.
• enqueue means insert an element at the rear
of a queue.
• dequeue means remove an element from the
front of a queue.
Queue Operations

• Think of queues as having a front and a


rear.
Queue

items[MAXQUEUE-
1]
. .
. .
. .
items[2] C Rear=2
items[1] B
items[0] A Front=0
Declaration of a Queue
/*Program of queue using array*/
# define MAX 5

int queue_arr[MAX];
int rear = -1;
int front = -1;
QUEUE OPERATIONS
• Initialize the queue
• Insert to the rear of the queue
• Remove (Delete) from the front of the queue
• Is the Queue Empty
• Is the Queue Full
• What is the size of the Queue
INITIALIZE THE QUEUE
•The queue is initialized by having the rear set to -1,
and front set to 0. Let us assume that maximum
number of the element we have in a queue is
MAXQUEUE elements as shown below.
items[MAXQUEUE-1]
. .
. .
.
items[1]
items[0] front=0
rear=-1
insert(&Queue, ‘A’)
• an item (A) is inserted at the Rear of the queue

items[MAXQUEUE
-1]
. .
. .
items[3]
items[2]
items[1]
items[0] A Front=0,
Rear=0
insert(&Queue, ‘B’)
• A new item (B) is inserted at the Rear of the queue

items[MAXQUEUE
-1]
. .
. .
items[3]
items[2]
items[1] B Rear=1

items[0] A Front=0
insert(&Queue, ‘C’)
• A new item (C) is inserted at the Rear of the queue

items[MAXQUEUE
-1]
. .
. .
items[3]
items[2] C Rear=2

items[1] B
items[0] A Front=0
insert(&Queue, ‘D’)
• A new item (D) is inserted at the Rear of the queue

items[MAXQUEUE-1]
. .
. .
items[3] D Rear=3

items[2] C
items[1] B
items[0] A Front=0
Insert Operation
insert()
{
int item;
if (rear==MAX-1)
printf("Queue Overflow\n");
else
{
if (front==-1) /*If queue is initially empty */
front=0;
printf("Input the element for adding in queue : ");
scanf("%d", &item);
rear=rear+1;
queue_arr[rear] = item ;
}
}/*End of insert()*/
char remove(&Queue)
• an item (A) is removed (deleted) from the Front of
the queue

items[MAXQUEUE-1]
. .
. .
items[3] D Rear=3
items[2] C
items[1] B Front=1
items[0] A
char remove(&Queue)

• Remove two items from the front of the queue.

items[MAXQUEUE-1]
. .
. .
items[3] D Rear=3
items[2] C Front=2
items[1] B
items[0] A
char remove(&Queue)

• Remove two items from the front of the queue.

items[MAXQUEUE-1]
. .
. .
items[3] D Front=Rear=3
items[2] C
items[1] B
items[0] A
char remove(&Queue)

• Remove one more item from the front of the queue.

items[MAXQUEUE-1]
. .
items[4] Front=4
items[3] D Rear=3
items[2] C
items[1] B
items[0] A
del()
Remove Operation
{
if (front == -1 || front > rear)
{
printf("Queue Underflow\n");
return ;
}
else
{
printf("Element deleted from queue is : %d\n",
item=queue_arr[front]);
front=front+1;
}
}/*End of del() */
INSERT / REMOVE ITEMS
• Assume that the rear= MAXQUEUE-1
items[MAXQUEUE-1] X rear=MAXQUEUE-1

. .
. .

items[3] D front=3

items[2] C
items[1] B
items[0] A

•What happens if we want to insert a new item into


the queue?
INSERT / REMOVE ITEMS
• What happens if we want to insert a new
item F into the queue?
• Although there is some empty space, the
queue is full.
• One of the methods to overcome this
problem is to shift all the items to occupy the
location of deleted item.
REMOVE ITEM
items[MAXQUEUE-1]

. .

. .

items[3] D Rear=3

items[2] C

items[1] B Front=1

items[0] A
REMOVE ITEM
items[MAXQUEUE-1]

. .

. .

items[3] D Rear=3

items[2] C

items[1] B Front=1

items[0] B
REMOVE ITEM
items[MAXQUEUE-1]

. .

. .

items[3] D Rear=3

items[2] C

items[1] C

items[0] B
REMOVE ITEM
items[MAXQUEUE-1]

. .

. .

items[3] D Rear=3

items[2] D

items[1] C

items[0] B
REMOVE ITEM
items[MAXQUEUE-1]

. .

. .

items[3] D

items[2] D Rear=2

items[1] C

items[0] B
INSERT / REMOVE ITEMS
• Since all the items in the queue are required
to shift when an item is deleted, this method
is not preferred.
• The other method is circular queue.
• When rear = MAXQUEUE-1, the next element
is entered at items[0] in case that spot is free.
Applications of Queue
• It is used to schedule the jobs to be processed
by the CPU.
• When multiple users send print jobs to a
printer, each printing job is kept in the printing
queue. Then the printer prints those jobs
according to first in first out (FIFO) basis.
• Breadth first search uses a queue data
structure to find an element from a graph.
Circular Queue
• A circular queue is one in which the insertion
of new element is done at the very first
location of the queue if the last location of the
queue is full.
• Suppose if we have a Queue of n elements
then after adding the element at the last index
i.e. (n-1)th , as queue is starting with 0 index,
the next element will be inserted at the very
first location of the queue which was not
possible in the simple linear queue.
Circular Queue operations
• The Basic Operations of a circular queue are
– InsertionCQ: Inserting an element into a circular
queue results in Rear = (Rear + 1) % MAX, where
MAX is the maximum size of the array.
– DeletionCQ : Deleting an element from a circular
queue results in Front = (Front + 1) % MAX, where
MAX is the maximum size of the array.
– TraversCQ: Displaying the elements of a circular
Queue.
Circular Array

• Wrapped around array rear=3

3
2
C
n-1 3 2 1 0 front=0 1
B
…… CBA
0 A

rear=3 front=0 n-1

108
EnQueue & DeQueue In Circular Array
• EnQueue • DeQueue
– rear = (rear + 1) MOD n – front = (front + 1) MOD n
– size=16

3 rear=3 front=1 3
2 2
1 BC 1 BC

0 A 0
n-1 n-1

109
Empty/Full In Circular Array

• When rear equals front, Queue is empty


• When (rear + 1) MOD n equals front, Queue
is full
• Circular array with capacity n at most can
hold n-1 items.

110
Circular Queue Representation
using Arrays
Let us consider a circular queue, which can hold
maximum (MAX) of six elements. Initially the queue is
empty.
Insertion and Deletion operations
on a Circular Queue
Insert new elements 11, 22, 33, 44 and 55 into the circular
queue. The circular queue status is:

Now, delete two elements 11, 22 from the circular queue.


The circular queue status is as follows:
Insertion and Deletion operations
on a Circular Queue
Again, insert another element 66 to the circular queue. The
status of the circular queue is:

Again, insert 77 and 88 to the circular queue. The status of


the Circular queue is:
Initialize the queue.

items[6] front=rear=6

items[5]
items[4]
items[3]
items[2]
items[1]
items[0]
Insert items into circular queue
 Insert A,B,C to the rear of the queue.

items[6] front=6

items[5]
items[4]
items[3]
items[2]
items[1]
items[0] A rear=0
Insert items into circular queue
 Insert A,B,C to the rear of the queue.

items[6] front=6

items[5]
items[4]
items[3]
items[2]
items[1] B rear=1

items[0] A
Insert items into circular queue
• Insert A,B,C to the rear of the queue.
items[6] front=6

items[5]
items[4]
items[3]
items[2] C rear=2

items[1] B
items[0] A
Remove items from circular queue

• Remove two items from the queue.

items[6]
items[5]
items[4]
items[3]
items[2] C rear=2

items[1] B

items[0] A front=0
Remove items from circular queue

• Remove two items from the queue.

items[6]
items[5]
items[4]
items[3]
items[2] C rear=2

items[1] B front=1

items[0] A
Remove items from circular queue

• Remove one more item from the queue.

items[6]
items[5]
items[4]
items[3]
items[2] C rear=front=2

items[1] B

items[0] A
• Insert D,E,F,G to the queue.

items[6] G rear=6

items[5] F
items[4] E

items[3] D

items[2] C front=2

items[1] B

items[0] A
• Insert H and I to the queue.

items[6] G
items[5] F
items[4] E

items[3] D

items[2] C front=2

items[1] B

items[0] H rear=0
• Insert H and I to the queue.

items[6] G
items[5] F
items[4] E

items[3] D

items[2] C front=2

items[1] I

items[0] H rear=0
• Insert J to the queue.
items[6] G
items[5] F
items[4] E

items[3] D

items[2] J front=rear=2

items[1] I

items[0] H
Declaration and Initialization of a Circular Queue.

/*Program of queue using array*/

# define MAX 5

int queue_arr[MAX];
int rear = -1;
int front = -1; ;
Insert
void enqueue(void)
Operation
{
int x;
if((front==0&&rear==max-1)||(front==rear+1)) //condition for full Queue
{
printf("Queue is overflow\n");return;
}
if(front==-1)
{
front=rear=0;
}
else
{
if(rear==max-1)
rear=0;
else
rear++;
}

printf("enter the no:\n");


scanf("%d",&x);
q[rear]=x;
printf("%d succ. inserted\n",x);
return;
}
void enqueue(void)
{
int x;
if((front==0&&rear==max-1)||(front==rear+1)) //condition for full Queue
{
printf("Queue is overflow\n");return;
}
if(front==-1)
{
front=rear=0;
}
else
{
if(rear==max-1)
rear=0;
else
rear++;
}

printf("enter the no:\n");


scanf("%d",&x);
q[rear]=x;
printf("%d succ. inserted\n",x);
return;
}
Remove Operation
void dequeue(void)
{
int y;
if(front==-1)
{
printf("q is underflow\n");return;
}
y=q[front];
if(front==rear)
{
front=rear=-1;
}
else
{
if(front==max-1)
{
front=0;
}
else
{
front++;
}
}
printf("%d succ. deleted\n",y);
return;
}
• void dequeue(void)
{
int y;
if(front==-1)
{
printf("q is underflow\n");return;
}
y=q[front];
if(front==rear)
{
front=rear=-1;
}
else
{
if(front==max-1)
{
front=0;
}
else
{
front++;
}
}
printf("%d succ. deleted\n",y);
return;
}
PRIORITY QUEUES
• The priority queue is a data structure in which
intrinsic ordering of the elements determines
the results of its basic operations.
• An ascending priority queue is a collection of
items into which items can be inserted
arbitrarily and from which only the smallest
item can be removed. On the other hand a
descending priority queue allows only the
largest item to be removed.
Priority QUEUE Operations
• Insertion
– The insertion in Priority queues is the same as in non-priority
queues.
• Deletion
– Deletion requires a search for the element of highest priority
and deletes the element with highest priority. The following
methods can be used for deletion/removal from a given Priority
Queue:
• After each deletion elements can be moved up in the array
decrementing the rear.
• The array in the queue can be maintained as an ordered
circular array
Exercises
• Write a method stutter that accepts a queue of Integers as
a parameter and replaces every element of the queue with
two copies of that element.
– [1, 2, 3] becomes [1, 1, 2, 2, 3, 3]

• Write a method mirror that accepts a queue of Strings as a


parameter and appends the queue's contents to itself in
reverse order.
– [a, b, c] becomes [a, b, c, c, b, a]

Potrebbero piacerti anche