DATA STRUCTURES (DS) Arrays, Stacks & Queues Courtesy : Goutam M V
Preview:
Citation preview
- Slide 1
- DATA STRUCTURES (DS) Arrays, Stacks & Queues Courtesy :
Goutam M V
- Slide 2
- Arrays Data Structures: Logical method of representing data in
memory. Two types 1. Simple data structures : built from
fundamental data types. Eg: Array, Structure 2. Compound data
structure : formed by using simple data types and are more complex.
Two types
- Slide 3
- 1. Linear DS :Single level DS, having elements in sequence Eg:
Stack, Queue, Linked list 2. Non-linear DS : multilevel DS Eg:
Tree, Graph
- Slide 4
- Array: Collection of homogeneous(same type) data elements,
which are stored in a linear fashion in memory,also called linear
DS. Structure: Collection of logically related fields, may be of
same or different types.
- Slide 5
- Stack: List (Linear DS) in which all insertions and deletions
are performed at one end (Top). Push: Insertion operation Pop :
Deletion operation Information processing : LIFO (Last In First
Out) order. Eg: Pile of books
- Slide 6
- Queue: List (Linear DS) in which insertion and deletion at two
ends Front : Deletion Rear : Insertion Info Processing : FIFO
(First In First Out) or First Come First Served (FCFS) Eg: Queue in
a railway reservation counter
- Slide 7
- Linked list: Linear collection of nodes, Last node contain null
pointer. First or Start It is a dynamic data structure
- Slide 8
- Non Linear DS Tree: Non-linear collection of nodes having
specially designated node called root, represented as an upside
down(root on top) Binary tree: Special class of tree, each node
except root cant have more than two nodes
- Slide 9
- Graph: Set of nodes (vertices) and set of arcs (edges),where
arc specified by pair of nodes. Directed graph (diagraph): if arcs
are ordered pairs.
- Slide 10
- Array Array name also called subscripted variable Two types:
One-dimensional arrays Multi-dimensional arrays One-dimensional
array: Syntax: type variable_name [size];
- Slide 11
- Eg: int arr [10]; Representation: LB : Lower bound UB : Upper
bound One dimensional array uses sequential allocation of memory
technique
- Slide 12
- Address Calculation - 1D &2D !!!!!!!
- Slide 13
- Address calculation (i th element) Address of arr [i] = B + (i
- LB) * S B : Base address or starting address S : Size of the
element in an array arr [LB:UB] i: array element Question:
- Slide 14
- Multidimensional array (Two dimensional) Having both rows and
columns, in which each element is specified by two subscripts. Eg:
int a [m] [n]; -> is an m by n (m*n) table having m rows and n
columns Size of array = m*n Syntax: type variable_name [no. of
rows] [no of columns];
- Slide 15
- Sequential allocation of two dimensional array Since comp
memory is linear,2D array stored using either Row major storage
Column major storage Using Row major storage Address of a [i] [j] =
B + [(i-LB1) * N + (j-LB2)]*S
- Slide 16
- Column major storage Address of a [i] [j] = B +
[(i-LB1)+(j-LB2)*M]*S
- Slide 17
- One dimensional Array Traversal : Visiting each element one
after other from start to end. Eg: a [5]; Algorithm for traversal A
be an array of size N. Traversal denoted by OPERATE. I denotes
index. Assume LB starts with 1. 1. Repeat for I=1,2,,N OPERATE on
A[I] 2. End
- Slide 18
- Traversal of 1D array //find sum of n integers #define S 20
//array size void main(){ int sum (int [],int);//function prototype
int a[s],n,i;//variables declared coutHIGH.
- Slide 25
- Algorithm 1. LOW=1 HIGH=N 2. Repeat while ( LOW A[MID]) Then
LOW=MID+1 else HIGH=MID-1} 5. Write(Unsuccessful search) 6.
End
- Slide 26
- Array in descending order 1.LOW=1 HGH=N 2. Repeat while (LOWA
[MID]) Then HIGH=MID-1 else LOW=MID+1} 5. Write (Unsuccessful
search) 6.End
- Slide 27
- Insertion of an element in an array A be an array of size N,
having M elements (M
- Algorithm 1. If (DATA>=A [M]) Then { A [M+1] = DATA go to
step 6} 2. POS=1 3. Repeat while (A [POS] DATA) Then{ write(DATA,
Cant be deleted) go to step 3 } else{ if ( A[I] = DATA ) Then {
Repeat for POS = I+1,I+2,,N{ A[ POS-1 ] = A[ POS ]} A[ N ] = 0 N =
N - 1go to step 3}}} 3.End
- Slide 37
- Sorting Arranging the elements in some specific order, ie
either ascending or descending order. Various sorting techniques
are Insertion sort Selection sort Bubble sort or Exchange sort
Quick sort, Shell sort, Merge sort, Heap sort
- Slide 38
- Insertion sort A be an array having N elements A[0],A[1],A
[N-1].Initially first element is assumed to be sorted. In first
pass a[1] is inserted to its proper place in sorted part of the
array. CURRENT : element to be placed during each pass. POS is used
for finding the appropriate position of CURRENT among the element
above it. I, J denotes array indices.
- Slide 39
- Algorithm 1. Repeat for I = 2,3,.,N up to step 5 2. CURRENT = A
[I] 3. POS = 1 4. Repeat while ((POS < I) AND (A [POS
- Algorithm 1. LAST = N 2. Repeat for PASS = 1,2,..,N-1 upto step
5 3. EXCHS = 0 4. Repeat for I= 1,2,.,LAST 1{ If (A [I]> A [I+1]
) Then{ TEMP = A [I] A [I] = A [I+1] A [I+1] = TEMP EXCHS = EXCHS +
1} } 5. If (EXCHS = 0) Then goto step 6 Else LAST + LAST -1 6.
End
- Slide 44
- Concatenation of two linear arrays Joining the elements of two
arrays to form a new array. First copy all the elements of one
array into new array and then copy other array elements to new
array. Size of new array will be the sum of two arrays.
- Slide 45
- Algorithm A and B be two arrays of size M and N respectively.
Concatenate A and B into array C of size M+N. I denotes array
index. 1. Repeat for I = 1,2,..,M C [I] = A [I] 2. Repeat for I =
1,2,.,N C [M + I ] = B [I] 3.End
- Slide 46
- Merging of two sorted arrays Process of combining two or more
sorted arrays into another array which is also sorted. We have two
techniques Concatenate two arrays and then sort using any sorting
algorithm Merge sort : Sorting while merging. Using this efficiency
increases
- Slide 47
- Algorithm A, B be two arrays of size M and N respectively
having elements in ascending order. We merge these two to C of size
M+N,ascending order. I,J, K and R denotes array indices.
- Slide 48
- 1. I =1,J = 1, K = 1 2. Repeat while (( I
- 1. I =1,J = N, K = 1 2. Repeat while (( I = 1)) { If (A [I]
M)Then{ Repeat for R = J,J-1,.,1 { C [ K ] = B [ R ] K=K+1}} else {
Repeat for R = I,I+1,.,M { C [K]= A [R] K=K+1}} 4. End
- Slide 51
- Two dimensional arrays Traversal : A be an array of size M * N.
We have to traverse and perform desired operation on each element.
Let it be OPERATE. I, J denotes array indices for rows and
columns.
- Slide 52
- Algorithm Traversal 1. Repeat for I = 1, 2,.,M {Repeat for J =
1, 2, ..,N OPERATE on A [I, J]} 2. End
- Slide 53
- "When you do the common things in life in an uncommon way, you
will command the attention of the world." - George Washington
- Slide 54
- Sum of elements on either diagonals of a N * N array A be an
array of size N * N. I,J denotes array indices.SUM stores sum of
elements on both diagonals.
- Slide 55
- Algorithm 1. SUM = 0 2. Repeat for I = 1, 2,.,N {Repeat for J =
1, 2, ,N {If ((I = J) OR ( I + J )= N + 1) Then SUM = SUM + A [ I,
J ]} } 3. Write SUM 4. End
- Slide 56
- Print upper half of a N * N array 1. Repeat for I = 1,2,,N {
Repeat for J = I,I+1,.,N Write (A [I, J] ) properly } 2. End
- Slide 57
- Find sum/difference of two N * M arrays It can be obtained by
adding or subtracting the corresponding elements of two
arrays.
- Slide 58
- Algorithm A and B be two arrays of size N * M. Let OP denote
the operation to be performed (+, -). I,J denotes array indices for
rows and columns respectively. We can do this 1. Without using any
additional array 2. Using an additional array of size N * M
- Slide 59
- Without using any additional array 1. Read OP 2. If (OP = +)
Then {Repeat for I = 1,2,.,N {Repeat for J = 1,2,..,M Write (A [I,
J] + B [I, J])}} 3. If (OP = - ) {Repeat for I = 1, 2, ..,N {Repeat
for J = 1,2,.,M Write(A [I, J] B [I, J])}} 4. End
- Slide 60
- Using an additional array C of size N*M 1. Read OP 2. If (OP =
+) Then {Repeat for I = 1,2,,N {Repeat for J = 1,2,.M C [I, J] = A
[I, J] + B [I, J]} } 3. If (OP = - ) Then {Repeat for I = 1,2,,N
{Repeat for J = 1,2,.M C [I, J] = A [I, J] - B [I, J]} } 4.
End
- Slide 64
- Limitations of arrays 1. The element must be homogeneous 2. The
insertion and deletion operation requires shifting of elements
which take time. 3. Size of array is fixed.
- Slide 65
- Class Test Question carrying 2 1/5 marks each 1. Define the
term data structure ? Give examples? 2. Address calculation of 1 D
array ?
- Slide 66
- Questions carrying 4 marks 1. Differentiate linear search and
binary search? Give a pgm for binary search in ascending
order?
- Slide 67
- 2. Program to delete an element from an unsorted array
- Slide 68
- 3. Explain Sorting ? Give a program for bubble sort ?
- Slide 69
- 4. What is merging ? Merge two arrays which are in ascending
order?
- Slide 70
- 5. Find sum and difference of two N * M arrays Using a third
variable for storing the sum.
- Slide 71
- Address calculation of 2 D array i, j denotes row and column
index where LB1
- START : Contains the address of first element NODES : Elements
of linked list NODE -> 1. information 2. link or pointer (for
storing the address of next node )
- Slide 77
- We use the address to access the elements in the logical order.
The list in memory may not be physically sequential. So Binary
search is impossible here.
- Slide 78
- The memory allocation of array is STATIC. ie the number of
elements is known in advance Dynamic memory allocation : Allocation
during runtime. DS like linked lists,trees and graphs uses this
techniques.
- Slide 79
- Stack (LIFO) Important subclass of lists in which insertion and
deletion of an element are allowed only at one end.(top) PUSH :
insertion POP : deletion TOP : The most accessible element BOTTOM :
Least accessible element.
- Slide 80
- We can implement the concept of stack in two ways 1.
Implemented as an array (Static) 2. Implemented as a linked
list(Dynamic)
- Slide 81
- Stack as an array (Array implementation of stack) Array is a
static data structure. So creation of a stack as an array requires
the number of elements in advance. Here is an example for an array
implementation of stack having size 5.
- Slide 82
- Operations on stack Add an element in to a stack -> PUSH
Delete an element from a stack -> POP Now we cant Push any other
elements as the stack is already full, If we do so an overflow
takes place.
- Slide 83
- Underflow When a stack is empty it contains no element, and it
is not possible to POP the stack,If we do so an underflow takes
place.
- Slide 84
- Insertion (PUSH)in a stack as an array S :stack N :size DATA :
Element to be inserted. TOP:The position of top element in the
stack
- Slide 85
- 1. If(TOP = N) { Write (Stack Overflow) go to step 4 } 2. TOP =
TOP + 1 3. S [TOP] = DATA 4. End
- Slide 86
- void push(int s[],int &top,int data) { if(top== size-1) {
cout info = data; newptr -> next = top; top = newptr;} else {
cout
- Function to pop a node void POP () { if (! top){ cout
- Way of writing operator between two operands is called infix
notation and the expression is called infix form expression High
level lang -> machine lang called the object code. Computer
assumes that arithmetic operation can take place in two operands
only.
- Slide 112
- Generally it is not. Solution : rework the expression and write
in a particular form known as postfix notation using stack which
operates in one operator and two operands. Three representations
are given below
- Slide 113
- A + B :Infix notation + AB:Prefix notation AB +:Postfix
notation
- Slide 114
- Infix to Prefix conversion (A B ) / C D + E Infix notation ( -
AB ) / C D + E ( / ( - AB )C ) D + E ( - ( / ( - AB ) C ) D) + E +
(- (/ ( - AB ) C ) D ) E + - / - ABCDEPrefix notation
- Slide 115
- Infix to Postfix ( A B )/ C D + EInfix notation Put parenthesis
to determine actual order. ie ((( A B ) / C ) D ) + E ((( AB - ) /
C) D ) + E (( AB C / ) D ) + E ( AB C / D - ) + E AB C / D E +
- Slide 116
- Advantage of Prefix and Postfix Here parenthesis are not
required to enclose the operations. Computers evaluates arithmetic
expressions given in INFIX form as 1. Convert INFIX to POSTFIX
using stack 2. Evaluate POSTFIX expression
- Slide 117
- Infix to Postfix conversion Here we uses a stack to perform the
operation. We have an algorithm for this conversion and is
EXP:Infix expression which we want to convert to postfix PE:Postfix
expression. STACK:Stack to hold operators and left parenthesis
- Slide 118
- We enclose the expression in parenthesis. Let left and right
parenthesis, operators and operands be called as symbols.EXP be
scanned from left to right and PE will be constructed from operands
of EXP and the operators popped from the stack, Finally leaving an
empty stack
- Slide 119
- 1. First of all enclose the EXP in parenthesis i.e. () 2. Read
next symbol of EXP and repeat steps 3 to 6 until the stack is empty
and go to step 7. 3. If the symbol read = operand then add it to PE
4. If the symbol read = ( then push it into STACK 5. If the symbol
read = operator then i) Repeat while (Priority of TOP (STACK)>=
Priority of operator) { POP operator from stack Add operator to PE}
ii ) Push operator in to stack STACK 6. If the symbol read = ) then
i) repeat while (TOP (STACK != ( ){ POP operator from stack Add
operator to PE} ii) Remove the ( 7. PE is the desired postfix
expression 8. End
- Slide 120
- Obtain the postfix notation for the following infix notation of
expression showing the content of the stack and postfix expression
formed after each step of conversion. A * B + ( C D / F ) Solution
? Here is the algorithm !!!
- Slide 121
- Symbol read = ( push it on stack = A add it to PE = * push it
on stack = B add it to PE = + push it on the stack = ( push it on
the stack = C add it to PE = - push it on stack = D add it to PE =
/ push it on stack = F add it to PE = )Pop the stack until TOP of
stack =( and add symbols popped to PE = )pop the stack and add the
symbol to PE
- Slide 122
- PE = AB * C DF / - +
- Slide 123
- Evaluation of PE
- Slide 124
- PE has no parenthesis, so it can be evaluated as two operands
and an operator at a time (except NOT operator). It is easy to
handle PE by the compiler than Infix Expression.
- Slide 125
- Algorithm
- Slide 126
- 1. Create an empty stack STACK 2. Read next symbol of postfix
expression PE and repeat up to step 4 until end of expression is
reached and go to step 5. 3. If (symbol read = operand ) Then PUSH
(STACK, symbol read) 4. If (symbol read = operator )Then{ If
(operator = NOT) Then{ POP (STACK, symbol) Evaluate the expression
so formed Push the result on to the stack} else{ POP (STACK, symbol
1) POP (STACK, symbol 2) Evaluate result = symbol 2 operator
symbol1 PUSH (STACK,result){} 5. POP (STACK,result) 6. End
- Slide 127
- Sure question for board exam !!!
- Slide 128
- Evaluate the given postfix notation of expression and show
status of stack for each operation. 500, 20, 30, +, 10, *, +
- Slide 129
- Refreshment Test 001
- Slide 130
- 1. Convert the expression ( TRUE && FALSE ) | | !
(FALSE | | TRUE) to postfix expression.Show the content of the
stack at every step ?
- Slide 131
- 2. Use a stack to evaluate the following postfix expression and
show the content of the stack after execution of each operation. AB
CD + E * + Where A = 5,B = 3,C = 5,D = 4, and E = 2
- Slide 132
- QUEUE FIFO (First In First Out)
- Slide 133
- Queue !!! Subclass of lists in which insertion and deletion
takes place at specific ends i e rear and front respectively.
Insertion :Rear (I a R) Deletion:Front It is a FIFO or FCFS (First
Come First Served) data structure. E g:Persons entering a cinema
hall
- Slide 134
- Operations on Queue 1. Creation of queue 2. Check for empty
queue 3. Check for full queue 4. Insert an element in queue 5.
Delete an element from queue 6. Display queue
- Slide 135
- Queue as an array (Array implementation of queue)
- Slide 136
- We have an example
- Slide 137
- Insertion in a queue as an array Q:Queue N:size of queue
DATA:Element to be inserted F:Front position in the queue R:Rear
position in the queue
- Slide 138
- Insertion 1. If ( R = N ) Then{ Write (Insertion not possible)
go to step 5} 2. R = R + 1 3. Q [ R ] = DATA 4. If (F = 0 ) Then F
= 1 5. End
- Slide 139
- Deletion 1. If ( F = 0 ) Then{ write ( Deletion not possible )
go to step 4} 2. DATA = Q [ F ] 3. If (F = R)Then{ F = 0 R = 0}
else F = F + 1 4. End
- Slide 140
- Is it an efficient one !!!
- Slide 141
- It is possible to come across a situation when the queue is
empty but it is not possible to insert any new element in the
queue. So its not acceptable. To overcome this we can implement the
queue as a stack where one end is fixed. i e fix the front
end.
- Slide 142
- It is considered to be inefficient It may take time if the
queue is very large. It may be costly Solution : Use the array
holding the queue as a circular queue.
- Slide 143
- Queue as a circular array
- Slide 144
- Here we have an example showing the processing of a circular
queue. Insertion in a circular queue as an array
- Slide 145
- Slide 146
- 1. If (R = N) Then R = 1 else R = R + 1 2. If (F = R )Then{
write (Queue overflow) go to step 5} 3. Q [R] = DATA 4. If (F = 0)
Then F = 1 5. End
- Slide 147
- Deletion from a circular queue as an array
- Slide 148
- 1. If ( F = 0) Then{ Write (Queue underflow) go to step 4} 2.
DATA = Q [F] 3. If (F = R )Then{ F = 0 R = 0} else{ If ( F = N)
Then F = 1 else F = F + 1} 4. End
- Slide 149
- 1. Write a program to delete element from the particular
position of an array. 2. Program to explain inline function 3.
Write a program to add element to the particular position of an
array. 4. Find the area of square, triangle, rectangle, and circle
by using function overloading
- Slide 150
- Linked Implementation of a queue
- Slide 151
- It overcomes the drawbacks of queue used as an array, because
the location in an array remain unused the array size may not be
enough to store the desired number of elements Here we use
front:point to first element rear:point to the last element
- Slide 152
- If the front pointer is null???? A new element can be inserted
at the end of the list after last node How to delete?
- Slide 153
- Insertion DATA:? FRONT:? REAR:? New element is inserted at the
rear end. Rear gets modified after insertion. AVAIL:? NEWPTR:?
- Slide 154
- 1. If (AVAIL = NULL) Then{ Write (Availability stack underflow)
go to step 6} 2. NEWPTR = AVAIL 3. AVAIL = LINK (AVAIL) 4. INFO
(NEWPTR) = DATA LINK (NEWPTR) = NULL 5. If (REAR = NULL ) Then{
FRONT = NEWPTR REAR = NEWPTR} else{ LINK (REAR ) = NEWPTR REAR =
NEWPTR} 6. End
- Slide 155
- Deletion FONT:? AVAIL:? TEMP:Temporary pointer
- Slide 156
- 1. If (FRONT = NULL)Then{ Write (Empty queue) go to step 8} 2.
TEMP = FRONT 3. Write (Deleted element is , INFO (TEMP) ) 4. FRONT
= LINK (FRONT) 5. If (FRONT = NULL ) Then REAR = NULL 6. LINK
(TEMP) = AVAIL 7. AVAIL = TEMP 8. End
- Slide 157
- Implementation of a queue as a Circular linked list
- Slide 158
- DEQUEUE ( DOUBLE ENDED QUEUE )
- Slide 159
- Linear list in which insertion and deletion are made to or from
either end of the structure. It is more general than a stack or a
queue.It is of two types. 1. Input restricted dequeue : Insertion
allowes at only one end. 2. Output restricted dequeue : Deletion
allowed only at one end
- Slide 160
- Priority Queue
- Slide 161
- Queue in which we can insert or delete elements from any
position depending on some priority. E g : In a multiuser system
CPU is needed by many programs and it is utilized by the program
one at a time depending on some priority.CPU is first used by
program having the highest priority.