0% found this document useful (0 votes)
40 views45 pages

Data Structures and Algorithms Spring 2023: Stack and Queue Applications

This document provides a summary of stack and queue applications and searching algorithms. It discusses stack applications including base conversion, evaluating postfix expressions, and converting infix to postfix expressions. Queue applications covered include reversing a stack, message/packet queueing, and job scheduling. Searching algorithms summarized are linear search, which sequentially checks each element, and binary search, which searches the middle element and halves the list. Hash tables are also introduced to improve search speed.

Uploaded by

Meii
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views45 pages

Data Structures and Algorithms Spring 2023: Stack and Queue Applications

This document provides a summary of stack and queue applications and searching algorithms. It discusses stack applications including base conversion, evaluating postfix expressions, and converting infix to postfix expressions. Queue applications covered include reversing a stack, message/packet queueing, and job scheduling. Searching algorithms summarized are linear search, which sequentially checks each element, and binary search, which searches the middle element and halves the list. Hash tables are also introduced to improve search speed.

Uploaded by

Meii
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

Data structures and algorithms

Spring 2023

STACK AND QUEUE APPLICATIONS

Lecturer: Do Thuy Duong


Contents
• Stack applications
• Queue applications
• Searching
• Linear
• Binary
• Hash table

2
2
Stack Applications

3
3
Stack Applications

• Application 1 - Base 10  Base B Conversion

• Application 2 - Evaluation of Postfix Expression

• Application 3 - Infix expression  postfix expression

4
Base Conversion
 Computers understand only numbers Words and letters are
translated into numbers in computer systems.
 Computer architecture supports the following number systems
 we need to study them and know the conversion technique
between them:

 Binary number system


 Octal number system
 Decimal number system
 Hexadecimal (Hex) number system

5
Base 10  Base B Conversion [2]
• Example: K=259 in base B=5 259
 5
• Answer: ? 51 (remainder=4)

• 259 = 2*53+0*52+1*5+4 51
 5
• 2014(5) 10 (remainder=1)

10
 5
2 (remainder=0)

2
 5
0 (remainder=2)

6
Base 10 Base B Conversion [3]
• Algorithm
• Find remainder
• Push found remainder to a stack
• Repeat from step 1 until we meet stop condition
• Pop them out to print - we have the result

7
Polish Expression [1]
• It takes time for computer to evaluate an arithmetic
expression in normal form (with parentheses)
2*(3+4)/5

((2*(3+4)+5)*6+7*8)*9

• Need a mathematical notation that allows to


parenthesis-free represent expressions  Polish
notation:
• Prefix: op arg1 arg2 / * 2 + 3 4 5
• Postfix: arg1 arg2 op 234+*5/

8
Polish Expression [2]
• Postfix notation is used to reduce computer
memory access and time for evaluating arithmetic
expression.

• Stack can be used to:


• Convert an normal expression (infix expression) to
postfix expression.

• Evaluate a postfix expression.

9
Polish Expression [3]
• Example 1
• Find the corresponding postfix & prefix notation of the
following expression

(A*B)+(C/D)
AB * C D / +
+ *AB / C D
(1+3)*((2-4)+5*7)

13+24-57*+*
*+13+-24*57

10
Polish Expression [4]
• Example 2
• Evaluate the following expressions

62+31-4*7+* − * / 15 − 7 + 1 1 3 2
=831-4*7+* = − * / 15 − 7 2 3 2
=824*7+* = − * / 15 5 3 2
=887+* =−*332
= 8 15 * =−92
= 120 =7

(6+2) * ((3-1)*4 +7) (15 / (7-(1+1)))*3 - 2

11
Infix expression  postfix expression [1]
• Define the precedence relation of some of the
operators:
• # is the special symbol to denote the bottom of
stack.

Operators precedence number


# 0
( 1
+ or - 2
* or / 3
14

12
Infix expression  postfix expression [2]

1. Examine the next element in the input


2. if it is an operand, output it (store for the result)
3. If it is left parenthese, push to stack.
4. If it is operator having higher priority than top, push to stack.
5. If it is operator having lower priority than top, then Pop all the
operators from the stack which are greater than or equal to in
precedence than that of the scanned operator. Then, push the
scanned operator to the stack.
6. If closing brackets, pop operators from stack and output until
an opening bracket is encountered. Pop and discard opening
bracket
7. If there is more input, go to step 1
8. If no more input, pop operators to output 15

13
Infix expression
 postfix expression [3]
- Scan infix expression from left to - If CS is right paren:
right while(TS != left paren)
- If CS is operand  print(CS) {
- If CS is left paren  push (S,CS) op = pop(S);
- If CS is operator:
print(op);
while (prec(CS)<prec(TS))
}
{
discard (TS);
op = pop(S);
print(op); - If no more infix:
} while (S != empty)
push(S,CS); {
op = pop(S);
print(op);
14 }
Infix expression postfix expression [4]
(1+3)*((2-4)+5*7)

15
Evaluation of Postfix Expression [1]
• Processing postfix using stack:
• Scan the expression from left to right.
• For each symbol, if it is an operand, we store
them for later operation (LIFO) push
• If the symbol is an operator, take out the latest 2 pop

operands stored and compute with the operator. pop

• Treat the operation result as a new operand and push


store it.
• Finally, we can obtain the result as the only one
operand stored (Top stack) pop

16
Evaluation of Postfix
• 6 2 + 3 1 - 4 * 7 + *
Expression [2]
• Scan the expression from left to right. 6 and 2 are operand, so
we push them to the stack.
• + is an operator, pop two latest operands from stack (6 & 2),
compute and push the result (8) back to stack.
• Continue scanning, 3 & 1 are operand push to stack.
• - is an operator pop  compute  push.
• 4 is an operand  push.
• * is an operator  pop  compute  push.
• 7 is an operand  push.
• + is an operator  pop  compute  push.
• * is an operator  pop  compute  push  final result
13

17
Queue Applications

18
Queue Applications

• Application 1 – Reversing a stack

• Application 2 – Message/Packet queueing

• Application 3 – Job scheduling

19
Reversing a Stack
stack
 //Reversing a stack D
C Pop from stack and
Queue q; Stack s; B insert into a queue
A
while(!s.isEmpty())
{ x =s.pop();
q.enqueue(x); queue
} D C B A
while (!q.isEmpty())
{ x = q.dequeue();
s.push(x);
} A
B 19
C Delete from queue and
D Push onto stack
20
Message/Packet Queueing [1]
A queue is used to integrate messages come from
different senders to receiver

21
Message/Packet Queueing [2]
A queue is used to control sending and receiving rate

22
Job Scheduling

23
Search algorithms

24
Search algorithms
Definition:
• A search algorithm is a method of locating a specific item of
information (called key) in a larger collection of data.
• This section discusses two algorithms for searching the contents of
an array.
• A new data structure name hash table can be used to improve the
searching speed

25
Linear search algorithm [1]
• This is a very simple algorithm.
• It uses a loop to sequentially step through an array, starting
with the first element.
• It compares each element with the value being searched for (key)
and stops when that key is found or the end of the array is reached.

26
Linear search algorithm [2]
Algorithm LinearSearch(A, n, key):
Input: An array A[0..n-1] storing n item.
key item for searching
Output: index of key in A, or -1 if not found

index  0
found  false
pos  -1
while ((index < n) && (!found))
if (A[index]==key)
found  true
pos  index
endif
index  index+1
endwhile
return found
27
Binary search algorithm [1]
• Binary search requires the array to be in order.
• The algorithm starts searching with the middle element.
• If the item is less than the middle element, it starts over searching
the first half of the list.
• If the item is greater than the middle element, the search starts
over starting with the middle element in the second half of the list.
• It then continues halving the list until the item is found.

28
Binary search algorithm [2]
• Example
Search 25 in 3 5 8 12 15 15 17 23 25 27
3 5 8 12 15 15 17 23 25 27
25 ? 15 15 17 23 25 27
25 ? 23 25 27
25 ? 25
It takes only 4 steps

29
Binary search algorithm [3]
 Algorithm BinarySearch(A, n, key):
Input: A sorted array A[0..n-1] storing n item.
: key item for searching
Output: index of key in A, or -1 if not found

Left  0 right  n-1


while (left < right)
mid (left+right)/2
if A[mid] < key
left mid+1
else if A[mid] > key
right mid-1
else
return mid
endwhile
return -1

30
Binary search algorithm [4]
Algorithm BinarySearch(A, left, right, key):
Input: A sorted array A[left..right].
key item for searching
Output: index of key in A, or -1 if not found

if (left > right)


return -1
else
mid  (left+right)/2
if A[mid] < key
return BinarySearch(A,mid+1,right,key)
else if A[mid] > key
return BinarySearch(A,left,mid-1,key)
else
return mid
endif

31
Binary search algorithm [5]
• Time complexity analysis: In each step we halves the input size.
• Recurrence

T(n)=T(n/2) + c T(n/2)=T(n/4)+c
T(n)=T(n/4) + c +c T(n/4)=T(n/8)+c
T(n)=T(n/8) + c + c + c
………………
T(n)=T(n/n) + c + … + c T(n)=T(1) + kc=log2n + C

k times
 T(n)=O(logn)

32
Linear search & Binary search
Linear search
• Simple & easy to implement
• Array can be in any order
• Inefficient (slow) compares to binary search: O(n)

Binary search
• More efficient than linear search (faster): O(logN)
• Array must be sorted

33
Hash table [1]
 Introduction
• Hash table is an effective data structure for implementing a
data set that only supports dictionary operators: Search,
Insert, Delete
• In general time complexity of the dictionary operators on a
hash table is O(1).
 The idea
• Hash table likes an array of some fixed size. It contains the
items.
• Item could consist of a key and additional data fields.

34
Hash table [2]
• The idea:
- Items are stored in the array, indexing from 0 to N-1
- The address of the item in the array is determined based
on the value of the key.
• address = h(key)
• h is called the hash function
• Example:
- We want to create a hash data structure to maintain a list of
students. For each student:
• The Key is the student ID - a number has 9 digits
• Data fields are student information: name, address, avatar …

35
Hash table [3]
• Example
• We uses an array with N=100 to store 100 items from A[0]
to A[99].
• The hash function:
• h(ID)=ID mod 100

[0] [1] [2] [3] [4] [5] [ 99]

...

36
Hash table [4]
• Example: address of an item [ 54 ]

• The hash function: ID 506643054


Name …
• h(ID)=ID % 100
• ID=506643054
• Address=54

[0] [1] [2] … [99]

…..

37
Hash table [5]
• Example
• ID=506642101 Address=1
• ID=506645202 Address=2
• ID=506648899 Address=99

• The operation maps ID (key) and address is called


hashing.

[0] [1] [2] … [ 54 ] [ 55 ] [99]


Number 281942902 Number 233667136 Number 506643548 Number 155778322

...

38
Hash table [6] ID 506643203

• Insert a new item


• Perform hashing on key to
find correspondingaddress.
• Add item to this address.
506643203 % 100=??

[0] [1] [2] [3] [ … ] [ 54 ] [99]


Number 281942902 Number 233667136 Number 506643548 Number 155778322

...

39
Hash table [7]
ID 506643203
• Insert a new item
• Perform hashing on key
to find corresponding
• Add item to this address
My hash
] [value
99] is
[3].
Number 155778322

[0] [1] [2] [99]


Number 281942902 Number 233667136

40
Hash table [8]
ID 506643402
• Collisions
• Collision occurs when the hashing
returns an address that is already
used by another valid item.
My hash
value is
[2].

[0] [1] [2] [3] [4] [5] [ 700]


Number 281942902 Number 233667136 Number 580625685 Number 506643548 Number 155778322

41
Hash table [9]
• Collision handling
• Two methods: Open hashing and Close hashing

• Open hashing (or Separate chaining)


• Each slot in the hash table is
the head of a linked list.
• All items that hash to a H(k)=k % 10
particular slot are placed
on that slot's linked list.
• Requires additional memory
outside the table

42
Hash table [10]
• Close hashing (or Open Addressing)
• Find another slot in the hash table to store the colliding items
• Probing method: If we try to place x in slot h(x) and find it
occupied, find alternative location h1(x), h2(x), ... Try each in
order, if all are occupied then the table is full.
• Linear probing
Handle collisions by placing the colliding item in the next
(circularly) available table slot.
• If h(k) is occupied, probe other slot hi(k) on the hash table

• If hi(k) is empty  store colliding item 43

• If all hi(k) are occupied  the table is full

43
Hash table [11]
• Linear probing example 0 38

• Consider a hash table of size 8 (N=8) 1


store integer key with the hash function: 2 18
h(k)=k % N = k % 8 3 19
26
• add(18), add(19), add(15), add(14) 4
5
• add(26)
6 14
• h(26)=2 is occupied
7 15
• Evaluate: h1(26)=(h(26)+1)%8=3 is occupied
• Evaluate: h2(26)=(h(26)+2)%8=4 is empty  stores 26 at 4.

• add(38) 44

44
Tutorial & next topic
• Preparing for the tutorial (at home):
• Practice with examples and exercises in
Tutorial 8.
• Preparing for the midterm test
• Preparing for next topic:
• Read textbook chapter 4 (4.1 – 4.3): Tree data
structure.
• Read supplementary book chapter 10 (10.4) and
45
chapter 12

45

You might also like