0% found this document useful (0 votes)
16 views31 pages

Unit 2

Uploaded by

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

Unit 2

Uploaded by

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

DATA STRUCTURES

Unit 2: Arrays, Stacks, and Queues (7 L)


• Arrays
• Introduction to Array,
• Applications of Array,
• Operations on Arrays:
• Traverse,
• Insert,
• Delete etc.
• Stacks
• Introduction to Stacks,
• Array representation of Stack,
• Operations on Stack: Push, Pop, etc.
• Applications of Stacks: Infix and Postfix Conversion, Evaluations of Infix and Postfix expressions.
• Queue
• Introduction to Queue,
• Array representation and implementation of queues,
• Operations of Queue,
• Applications of Queue,
• Types of Queue: Circular Queue, Priority Queue, Double ended Queue.
• Operations on each type of Queue and their Applications.
Arrays
 An array is a collection of items stored at contiguous memory locations.
 The idea is to store multiple items of the same type together.
 This makes it easier to calculate the position of each element by simply adding an offset to a base
value, i.e., the memory location of the first element of the array (generally denoted by the name of the
array).
 The base value is index 0 and the difference between the two indexes is the offset.
 Types of indexing in an array:
0 (zero-based indexing): The first element of the array is indexed by a subscript of 0
1 (one-based indexing): The first element of the array is indexed by the subscript of 1
n (n-based indexing): The base index of an array can be freely chosen.
Arrays
 Advantages of using arrays:
 Arrays allow random access to elements. This makes accessing elements by position faster.
 Arrays have better cache locality that can make a pretty big difference in performance.
 Disadvantages of using arrays:
 You can’t change the size. Here, Insertion and deletion are difficult as the elements are stored in
consecutive memory locations and the shifting operation is costly too.
 Application of Array:
 Array stores data elements of the same data type.
 Arrays can be used for CPU scheduling.
 Used to Implement other data structures like Stacks, Queues, Heaps, Hash tables, etc.
Arrays
 Advantages of using arrays:
 Arrays allow random access to elements. This makes accessing elements by position faster.
 Arrays have better cache locality that can make a pretty big difference in performance.
 Disadvantages of using arrays:
 You can’t change the size. Here, Insertion and deletion are difficult as the elements are stored in
consecutive memory locations and the shifting operation is costly too.
 Application of Array:
 Array stores data elements of the same data type.
 Arrays can be used for CPU scheduling.
 Used to Implement other data structures like Stacks, Queues, Heaps, Hash tables, etc.
Arrays
 Operation on arrays: o In the example array, elements from index J (4) to index 8 have to
 Insertion: moved one position backwards so that a new element can be stored at

o Algorithm Insert LA (DATA, N, ITEM, LOC) index J(4)

o o Initially
Description: This algorithm inserts new element ITEM in linear array DATA with N elements
o If LOC=1 it means the element has to insert in beginning
o If LOC =N+1 it means the element have to be inserted at the end
o If LOC = J it means the elements have to be inserted at Jth Location
o o After movement of elements
Begin
o Step 1: [Initialize counter I with index of last element]
o I=N
o Step 2: While I>=LOC repeat steps 3 and 4
o Step 3: [Move the current element one position backwards]
o o After Insertion
DATA[I+1]=DATA[I]
o Step 4: [Decrement counter I]
o I=I-1
o Step 5:[Insert new element at the Location]
o DATA[LOC]=ITEM
o o Note:- for each one of these three cases the count of elements
Step 6:[ Update total under of array elements]
o N=N+1 increases by 1

o Exit
Arrays
 Operation on arrays: o In the example array, elements from index J (4) to index 8 have to
 Deletion: moved one position backwards so that a new element can be deleted

o Algorithm Deletion LA (DATA, N, ITEM, LOC) (overwrite) at index J(4)

o o Initially
Description: This algorithm Delete element ITEM in linear array DATA with N elements
o If LOC=1 it means the element has to delete in beginning
10 30 21 56 27 48 89 51
o If LOC =N it means the element have to be deleted at the end
1 2 3 4 5 6 7 8 9 10 11
o If LOC = J it means the elements have to be deleted at Jth Location 12

o Begin
o o After movement of elements
Step 1: [Initialize counter I with index of last element]
o I=N
10 30 21 56 27 48 89 51
o Step 2: While I>=LOC repeat steps 3 and 4
o Step 3: [Move the current element one position backwards] o 1 2 3 4 5 6 7 8 9 10 11
o DATA[LOC]=DATA[LOC+1] 12

o Step 4: [increment counter LOC]


o LOC=LOC+1 o After Deletion
10 30 21 27 48 89 51
o Step 6:[ Update total under of array elements]
o N=N-1
o Exit
o Note:- for each one of these three cases the count of elements
decreases by 1
Arrays
 Operation on arrays:
 Traversal:
o Algorithm Traversal LA (DATA, N, LOC)
o Description: This algorithm Traverse ITEMs in linear array DATA with N elements
o If LOC=1 it means the traversal starts from beginning
o If LOC = J it means the traversal starts from beginning Location
o Begin
o Step 1: [Initialize counter I with index of Last element]
o I=N
o Step 2: While I >= LOC repeat steps 3 and 4
o Step 3: [Move the current element one position backwards]
o DATA[LOC]
o Step 4: [increment counter LOC]
o LOC=LOC+1
o Exit
Stack
 Stack is a linear data structure which follows a particular order in
which the operations are performed. The order may be LIFO(Last In First
Out) or FILO(First In Last Out).
 Mainly the following three basic operations are performed in the stack:
 Push: Adds an item in the stack. If the stack is full, then it is said to
be an Overflow condition.
 Pop: Removes an item from the stack. The items are popped in the
reversed order in which they are pushed. If the stack is empty, then it
is said to be an Underflow condition.
 Peek or Top: Returns top element of stack.
 isEmpty: Returns true if stack is empty, else false.
Stack
 There are many real-life examples of a stack.
 Consider the simple example of plates stacked over one another in a canteen.
 The plate which is at the top is the first one to be removed, i.e. the plate which has been placed at the
bottommost position remains in the stack for the longest period of time.
 So, it can be simply seen to follow LIFO/FILO order.
Stack
 Computer Science Application of stack.
 Decimal to binary conversion.
Infix to Postfix /Prefix conversion.
Evaluation of postfix expression.
 Used in many algorithms like Tower of Hanoi, DFS, ..
 Stack is used in recursion to store return address.
 String reversal is also a another application.
Stack
 Array Representation of stack:
 Top provides top value of the stack without actually removing it.
 First we should learn about procedures to support stack functions.

i. peek() ii. isempty()


o begin procedure peek o begin procedure isempty
return stack[top] if top equals to -1
end procedure return true
else
return false
ii. isfull() end procedure
o begin procedure isfull
if top equals to
SIZE
return true
else
return false
end procedure
Stack
 Operation on stack:
 Item denotes the ith item in the stack;
 0 and SIZE-1 denote the index range of the array in use;
 TOP is the position of the array up to which it is filled with the items of the stack.
 Push: Adds an item in the stack. If the stack is full, then it is said to be an overflow condition.

Push(top, item)
begin
if top = SIZE-1 then stack full
top = top + 1
stack (top) : = item;
end
Stack
 Operation on stack:
 Item denotes the ith item in the stack;
 0 and SIZE-1 denote the index range of the array in use;
 TOP is the position of the array up to which it is filled with the items of the stack.
 Pop: Removes an item from the stack. The items are popped in the reverse order from when they are pushed. If the stack
is empty, then it is said to be an underflow condition.

Pop(top)
begin
if top = -1 then stack empty;
item := stack(top);
top = top - 1;
end;
Application of Stack

 Infix: An infix expression is an expression in which operators (+, -, *, /) are written between the two operands.
 For example
 A+B
 A+B-C
 (A + B) + (C - D)
 Postfix: Operator is written after the operand. It is :also known as Reverse Polish Notation.
 For example:
 AB+
 AB+C-
 AB+CD-+
Application of Stack
 Why postfix representation of the expression?

 The compiler scans the expression either from left to right or from right to left.
 Consider the below expression: a + b * c + d
 The compiler first scans the expression to evaluate the expression b * c, then again scan the expression to add a to it.
The result is then added to d after another scan.
 The repeated scanning makes it very in-efficient.
 It is better to convert the expression to postfix(or prefix) form before evaluation.
 The corresponding expression in postfix form is: abc*+d+.
 The postfix expressions can be evaluated easily using a stack.
 We will cover postfix expression evaluation in a separate post.
Application of Stack
 Infix to Postfix:
1. Add ) on the right of infix expression.
2. Scan the infix expression from left to right.
3. If the scanned character is an operand, output it.
4. Else,
1 If the precedence of the scanned operator is greater than
the precedence of the operator in the stack(or the stack is
empty or the stack contains a ‘(‘ , push it.
2 Else, Pop all the operators from the stack which are
greater than or equal to in precedence than that of the
scanned operator. After doing that, Push the scanned
operator to the stack. (If you encounter parenthesis while
popping then stop there and push the scanned operator in
the stack.)
5. If the scanned character is an ‘(‘, push it to the stack.
6. If the scanned character is an ‘)’, pop the stack and and
output it until a ‘(‘ is encountered, and discard both the
parenthesis.
6. Repeat steps 3-6 until infix expression is scanned.
7. Print the output
Application of Stack
Evaluation of Postfix Expression
 The expressions written in postfix form are evaluated
faster compared to infix notation as parenthesis are not
required in postfix.

Following is algorithm for evaluation postfix expressions.


1) Create a stack to store operands (or values).
2) Scan the given expression and do following for every
scanned element.
…..a) If the element is a number, push it into the stack
…..b) If the element is a operator, pop operands for the
operator from stack. Evaluate the operator and push the
result back to the stack
3) When the expression is ended, the number in the stack is the
final answer
Queue
A Queue is a linear structure in which the operations are performed in a particular order.
The order is First In First Out (FIFO).
A good example of a queue is any queue of consumers for a resource where the consumer that came first is served first.
The difference between stacks and queues is in removing.
In a stack we remove the item the most recently added; in a queue, we remove the item the least recently added.
Queue
Array Implementation of Queue:
 There are two variables i.e. FRONT and REAR, that are implemented in the case of every queue.
 Front and REAR variables point to the position from where insertions and deletions are performed in a queue.
 Initially, the value of FRONT and queue is -1 which represents an empty queue.
 Array representation of a queue containing 5 elements along with the respective values of FRONT and REAR, is shown
in the following figure.
Queue
Enqueue:
 Check if the queue is already full by comparing REAR to MAX - 1. if so, then return an overflow error.
 If the item is to be inserted as the first element in the list, in that case set the value of FRONT and REAR to 0 and insert
the element at the REAR end.
 Otherwise keep increasing the value of REAR and insert each element one by one having REAR as the index.
Step 1: IF REAR = MAX - 1
Write OVERFLOW
Go to step 4
[END OF IF]
Step 2: IF FRONT = -1 and REAR = -1
SET FRONT = REAR = 0
ELSE
SET REAR = REAR + 1
[END OF IF]
Step 3: Set QUEUE[REAR] = NUM
Step 4: EXIT
Queue
Dequeue:
 If, the value of FRONT is -1 . write an underflow message and exit.
 Otherwise, check if value of FRONT is equal to REAR then set FRONT and REAR as -1
 Otherwise keep increasing the value of FRONT and return the item stored at the FRONT end of the queue at each time.
 Algorithm
Step 1: IF FRONT = -1
Write UNDERFLOW go to step 2
ELSE IF FRONT=REAR
SET VAL = QUEUE[FRONT]
SET FRONT=-1, REAR=-1
ELSE
SET VAL = QUEUE[FRONT]
SET FRONT = FRONT + 1
[END OF IF]
Step 2: EXIT
Application of Queue

 When a resource is shared among multiple consumers. Examples include CPU scheduling, Disk Scheduling.
When data is transferred asynchronously (data not necessarily received at same rate as sent) between two processes. Examples
include IO Buffers, pipes, file IO, etc.
Circular Queue

Why circular queue?


 In a normal Queue, we can insert elements until queue becomes full. But once queue becomes full, we can not insert the
next element even if there is a space in FRONT of queue.

 Circular Queue is a linear data structure in which the operations are performed based on FIFO (First In First Out)
principle and the last position is connected back to the first position to make a circle. It is also called ‘Ring Buffer’.
Circular Queue
Circular Queue
Operations on Circular Queue:
 Front: Get the FRONT item from queue.
 Rear: Get the last item from queue.
 enQueue(value)
 This function is used to insert an element into the circular queue.
 In a circular queue, the new element is always inserted at Rear position.
 deQueue()
 This function is used to delete an element from the circular queue.
 In a circular queue, the element is always deleted from FRONT position.
Circular Queue
enQueue(value)
 First, we will check whether the Queue is full or not.  Algorithm to insert an element in a circular queue
 There are two cases in which the element cannot be inserted:
 When FRONT ==0 && REAR = MAX-1, which  Step 1: IF (REAR+1)%MAX == FRONT
means that FRONT is at the first position of the Queue  Write " OVERFLOW "
and REAR is at the last position of the Queue.
 FRONT== REAR + 1;  Goto step 4
The above two condition can be combined as  [End OF IF]
(REAR+1)%MAX== FRONT
 Step 2: IF FRONT == -1 and REAR == -1
 Initially the FRONT and REAR are set to -1. When we insert  SET FRONT = REAR = 0
the first element in a Queue, FRONT and REAR both are set
 ELSE
to 0.
 Scenarios for inserting an element when Q is not empty.  SET REAR = (REAR + 1) % MAX
 There are two scenarios in which queue is not full or empty  [END OF IF]
 If REAR != MAX - 1, When we insert a new element,
the REAR gets incremented, i.e., REAR=REAR+1.  Step 3: SET QUEUE[REAR] = VAL
 If FRONT != 0 and REAR = MAX - 1, it means that  Step 4: EXIT
queue is not full, then set the value of REAR to 0 and
insert the new element there.
The above two conditions can be combined and written as
REAR=(REAR+1)%MAX
Circular Queue
deQueue()
 Algorithm to delete an element from the circular queue
 The steps of dequeue operation are given below:
 Step 1: IF FRONT == -1
 First, we check whether the Queue is empty or not. If  Write " UNDERFLOW "
the queue is empty, we cannot perform the dequeue  Goto Step 4
 [END of IF]
operation.
 Step 2: SET VAL = QUEUE[FRONT]
 If there is only one element left which is to be deleted,
 Step 3: IF FRONT == REAR
then the FRONT and REAR are reset to -1.  SET FRONT = REAR = -1
 When there is more than one element then there are  ELSE
two situations:  SET FRONT = (FRONT + 1)%MAX

 If FRONT == MAX -1, then we set front to 0  [END of IF]


 [END OF IF]
 If FRONT!=MAX-1, then front needs to be
 Step 4: EXIT
incremented for deletion.
 The above condition can be combined and written as:
FRONT= (FRONT+1)%MAX
Priority Queue
Priority Queue is an extension of queue with following properties.
 Every item has a priority associated with it.
 An element with high priority is dequeued before an element with low priority.
 If two elements have the same priority, they are served according to their order in the queue.
 In the below priority queue, element with MAXimum ASCII value will have the highest priority.
Priority Queue
A typical priority queue supports following operations.
 insert(item, priority): Inserts an item with given priority.
 getHighestPriority(): Returns the highest priority item.
 deleteHighestPriority(): Removes the highest priority item.
How to implement priority queue?
 Using Array: A simple implementation is to use array of following structure.
struct item {
int item;
int priority;
}
 insert() operation can be implemented by adding an item at end of array in O(1) time.
 getHighestPriority() operation can be implemented by linearly searching the highest priority item in array. This
operation takes O(n) time.
 deleteHighestPriority() operation can be implemented by first linearly searching an item, then removing the item by
moving all subsequent items one position back.
Deque
Deque or Double Ended Queue is a generalized version of Queue data structure that allows insert and delete at both ends.
Operations on Deque:
 Mainly the following four basic operations are performed on queue:
 insertFront(): Adds an item at the FRONT of Deque.
 insertLast(): Adds an item at the REAR of Deque.
 deleteFront(): Deletes an item from FRONT of Deque.
 deleteLast(): Deletes an item from REAR of Deque.
In addition to above operations, following operations are also supported
 getFront(): Gets the FRONT item from queue.
 getRear(): Gets the last item from queue.
 isEmpty(): Checks whether Deque is empty or not.
 isFull(): Checks whether Deque is full or not.
REFERENCES
1. https://www.geeksforgeeks.org/
2. Thareja, R. (2014). Data structures using C. Oxford University.
3. Lipschutz, S. (2003). Schaum's outline of theory and problems of data structures.
McGraw-Hill.

You might also like