Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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
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);
}
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.
• 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
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
...
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.
• 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
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)
items[MAXQUEUE-1]
. .
. .
items[3] D Rear=3
items[2] C Front=2
items[1] B
items[0] A
char remove(&Queue)
items[MAXQUEUE-1]
. .
. .
items[3] D Front=Rear=3
items[2] C
items[1] B
items[0] A
char remove(&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
. .
. .
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
3
2
C
n-1 3 2 1 0 front=0 1
B
…… CBA
0 A
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
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:
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
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
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
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.
# 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++;
}