0% found this document useful (0 votes)
8 views79 pages

Dsa UNIT-2

Uploaded by

ajithtech21600
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)
8 views79 pages

Dsa UNIT-2

Uploaded by

ajithtech21600
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/ 79

UNIT-2

SYLLABUS
Arrays, Stacks & Queues

• Concepts; Basic operations & their algorithms:


Transverse, Insert, Delete, Sorting of data in
these data structures; Prefix, Infix, Postfix
Notations.
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.
• It is one of the simplest data structures where
each data element can be randomly accessed by
using its index number.
• Array is a type of linear data structure. These data
structures come into picture when there is a
necessity to store multiple elements of similar
nature together at one place.
Properties of array

• There are some of the properties of an array that


are listed as follows -
• Each element in an array is of the same data type.
• Elements in the array are stored at contiguous
memory locations from which the first element is
stored at the smallest memory location.
• Elements of the array can be randomly accessed
since we can calculate the address of each
element of the array with the given base address
and the size of the data element.
Concept of Array
• The difference between an array index and a memory
address is that the array index acts like a key value to
label the elements in the array. However, a memory
address is the starting address of free memory
available.
• Following are the important terms to understand the
concept of Array.
• Element − Each item stored in an array is called an
element.
• Index − Each location of an element in an array has a
numerical index, which is used to identify the element.
Example
Syntax
Advantages and Disadvantages
Advantages of Array
• Array provides the single name for the group of variables of the same
type. Therefore, it is easy to remember the name of all the elements of an
array.
• Traversing an array is a very simple process; we just need to increment the
base address of the array in order to visit each element one by one.
• Any element in the array can be directly accessed by using the index.
Disadvantages of Array
• Array is homogenous. It means that the elements with similar data type
can be stored in it.
• In array, there is static memory allocation that is size of an array cannot be
altered.
• There will be wastage of memory if we store less number of elements
than the declared size
Insertion Operation

• In the insertion operation, we are adding one


or more elements to the array. Based on the
requirement, a new element can be added at
the beginning, end, or any given index of
array. This is done using input statements of
the programming languages.
Algorithm
Following is an algorithm to insert elements into a Linear Array until we reach the end
of the array
Deletion Operation

• In this array operation, we delete an element


from the particular index of an array. This
deletion operation takes place as we assign
the value in the consequent index to the
current index.
Algorithm
Consider LA is a linear array with N elements and K is a positive integer such that K<=N. Following is the
algorithm to delete an element available at the Kth position of LA.
Search Operation
• Searching an element in the array using a key;
The key element sequentially compares every
value in the array to check if the key is present
in the array or not.
Algorithm
Consider LA is a linear array with N elements and K is a positive integer such that K<=N. Following is the
algorithm to find an element with a value of ITEM using sequential search.
Traversal Operation
• This operation traverses through all the
elements of an array. We use loop statements
to carry this out.
Algorithm
Following is the algorithm to traverse through all the elements present in a Linear
Array −
Sorting of Array

Algorithm :
• Take the size of the array from the user.
• Declare an array of given input size.
• Take the input of all elements of the array.
• Now run a for loop from 0 to size-1.
• And for every element check it from all the next elements to it. If
the element is greater than swap that number.
• In this way the array will get sorted in ascending order.

https://www.geeksforgeeks.org/sorting-algorithms/
Stacks
• Stack is a linear data structure that follows a
particular order in which the operations are
performed.
• The insertion of a new element and removal of an
existing element takes place at the same end
represented as the top of the stack.
• The order may be LIFO(Last In First Out) or
FILO(First In Last Out). LIFO implies that the
element that is inserted last, comes out first and
FILO implies that the element that is inserted
first, comes out last.
Stacks
It is named stack because it has the similar operations as the real-world stacks, for
example – a pack of cards or a pile of plates, etc.
Stacks
• There are many real-life examples of a stack.
Consider an example of plates stacked over
one another in the 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(Last In First
Out)/FILO(First In Last Out) order.
LIFO( Last In First Out ):

• This strategy states that the element that is


inserted last will come out first. You can take a
pile of plates kept on top of each other as a
real-life example. The plate which we put last
is on the top and since we remove the plate
that is at the top, we can say that the plate
that was put last comes out first.
Stacks
Standard Stack Operations

• The following are some common operations implemented on the


stack:
• push(): When we insert an element in a stack then the operation is
known as a push. If the stack is full then the overflow condition
occurs.
• pop(): When we delete an element from the stack, the operation is
known as a pop. If the stack is empty means that no element exists
in the stack, this state is known as an underflow state.
• isEmpty(): It determines whether the stack is empty or not.
• isFull(): It determines whether the stack is full or not.'
• peek(): It returns the element at the given position.
• count(): It returns the total number of elements available in a stack.
• change(): It changes the element at the given position.
• display(): It prints all the elements available in the stack.
Stacks
Basic Operations on Stacks

• The most fundamental operations in the stack


ADT include: push(), pop(), peek(), isFull(),
isEmpty(). These are all built-in operations to
carry out data manipulation and to check the
status of the stack.
• Stack uses pointers that always point to the
topmost element within the stack, hence
called as the top pointer.
PUSH operation

• The steps involved in the PUSH operation is given below:


• Before inserting an element in a stack, we check whether the stack
is full.
• If we try to insert the element in a stack, and the stack is full, then
the overflow condition occurs.
• When we initialize a stack, we set the value of top as -1 to check
that the stack is empty.
• When the new element is pushed in a stack, first, the value of the
top gets incremented, i.e., top=top+1, and the element will be
placed at the new position of the top.
• The elements will be inserted until we reach the max size of the
stack.

PUSH operation
POP operation

• The steps involved in the POP operation is given


below:
• Before deleting the element from the stack, we
check whether the stack is empty.
• If we try to delete the element from the empty
stack, then the underflow condition occurs.
• If the stack is not empty, we first access the
element which is pointed by the top
• Once the pop operation is performed, the top is
decremented by 1, i.e., top=top-1.
POP operation
Insertion: push()

• push() is an operation that inserts elements into


the stack. The following is an algorithm that
describes the push() operation in a simpler way.
Deletion: pop()

• pop() is a data manipulation operation which


removes elements from the stack. The following
pseudo code describes the pop() operation in a
simpler way.
peek()

• The peek() is an operation retrieves the topmost


element within the stack, without deleting it. This
operation is used to check the status of the stack
with the help of the top pointer.
isFull()

• isFull() operation checks whether the stack is full.


This operation is used to check the status of the
stack with the help of top pointer.
isEmpty()

• The isEmpty() operation verifies whether the


stack is empty. This operation is used to check the
status of the stack with the help of top pointer.
Working of Stack Data Structure

• The operations work as follows:


• A pointer called TOP is used to keep track of the top
element in the stack.
• When initializing the stack, we set its value to -1 so that we
can check if the stack is empty by comparing TOP == -1.
• On pushing an element, we increase the value of TOP and
place the new element in the position pointed to by TOP.
• On popping an element, we return the element pointed to
by TOP and reduce its value.
• Before pushing, we check if the stack is already full
• Before popping, we check if the stack is already empty
Working of Stack Data Structure
Example
Output

In the example, we have created a stack of strings named languages.


Here, we have used the push() method to add elements to the stack.
We have then used the top() method to display the top element.
Applications of Stack

The following are the applications of the stack:


• Balancing of symbols: Stack is used for balancing
a symbol.
• As we know, each program has an
opening and closing braces; when the opening
braces come, we push the braces in a stack, and
when the closing braces appear, we pop the
opening braces from the stack. Therefore, the net
value comes out to be zero. If any symbol is left in
the stack, it means that some syntax occurs in a
program.
Applications of Stack

• String reversal: Stack is also used for reversing a string. For example, we want to reverse a
"javaTpoint" string, so we can achieve this with the help of a stack.
First, we push all the characters of the string in a stack until we reach the null character.
After pushing all the characters, we start taking out the character one by one until we reach
the bottom of the stack.
• UNDO/REDO: It can also be used for performing UNDO/REDO operations. For example, we
have an editor in which we write 'a', then 'b', and then 'c'; therefore, the text written in an
editor is abc. So, there are three states, a, ab, and abc, which are stored in a stack. There
would be two stacks in which one stack shows UNDO state, and the other shows REDO state.
If we want to perform UNDO operation, and want to achieve 'ab' state, then we implement
pop operation.
• Recursion: The recursion means that the function is calling itself again. To maintain the
previous states, the compiler creates a system stack in which all the previous records of the
function are maintained.
• DFS(Depth First Search): This search is implemented on a Graph, and Graph uses the stack
data structure.

Applications of Stack

• Backtracking: Suppose we have to create a path to solve a maze problem.


If we are moving in a particular path, and we realize that we come on the
wrong way. In order to come at the beginning of the path to create a new
path, we have to use the stack data structure.
• Expression conversion: Stack can also be used for expression conversion.
This is one of the most important applications of stack. The list of the
expression conversion is given below:
Infix to prefix, Infix to postfix, Prefix to infix ,Prefix to postfix, Postfix to infix.
• Memory management: The stack manages the memory. The memory is
assigned in the contiguous memory blocks. The memory is known as stack
memory as all the variables are assigned in a function call stack memory.
The memory size assigned to the program is known to the compiler. When
the function is created, all its variables are assigned in the stack memory.
When the function completed its execution, all the variables assigned in
the stack are released.
Sorting a stack
• Sort a stack using a temporary stack
• Sort a Stack using Recursion
Sort a stack using a temporary stack

• Algorithm:
• Create a temporary stack say tmpStack.
• While input stack is NOT empty do this:
– Pop an element from input stack call it temp
– while temporary stack is NOT empty and top of
temporary stack is greater than temp,
pop from temporary stack and push it to the input
stack
– push temp in temporary stack
• The sorted numbers are in tmpStack
Sort a Stack using Recursion

• The idea of the solution is to hold all values in Function Call


Stack until the stack becomes empty. When the stack
becomes empty, insert all held items one by one in sorted
order. and then print the stack.

Follow the steps mentioned below to implement the idea:


• Create a stack and push all the elements in it.
• Call sortStack(), which will pop an element from the stack
and pass the popped element to function sortInserted(),
then it will keep calling itself until the stack is empty.
• Whenever sortInserted() is called it will insert the passed
element in stack in sorted order.
• Print the stack
Queues
• A Queue is defined as a linear data structure
that is open at both ends and the operations
are performed in First In First Out (FIFO) order.
• We define a queue to be a list in which all
additions to the list are made at one end, and
all deletions from the list are made at the
other end.
FIFO Principle of Queue:

• A Queue is like a line waiting to purchase tickets, where


the first person in line is the first person served. (i.e.
First come first serve).
• Position of the entry in a queue ready to be served,
that is, the first entry that will be removed from the
queue, is called the front of the
queue(sometimes, head of the queue), similarly, the
position of the last entry in the queue, that is, the one
most recently added, is called the rear (or the tail) of
the queue. See the below figure.
Queue Representation:

• Like stacks, Queues can also be represented in an


array: In this representation, the Queue is
implemented using the array. Variables used in
this case are-
• Queue: the name of the array storing queue
elements.
• Front: the index where the first element is stored
in the array representing the queue.
• Rear: the index where the last element is stored
in an array representing the queue.
Working of Queue

• Queue operations work as follows:


• two pointers FRONT and REAR
• FRONT track the first element of the queue
• REAR track the last element of the queue
• initially, set value of FRONT and REAR to -1
Queues
Characteristics of Queue:

• Queue can handle multiple data.


• We can access both ends.
• They are fast and flexible.
Applications of Queue

Due to the fact that queue performs actions on first in first out basis
which is quite fair for the ordering of actions. There are various
applications of queues discussed as below.
• Queues are widely used as waiting lists for a single shared resource
like printer, disk, CPU.
• Queues are used in asynchronous transfer of data (where data is
not being transferred at the same rate between two processes) for
eg. pipes, file IO, sockets.
• Queues are used as buffers in most of the applications like MP3
media player, CD player, etc.
• Queue are used to maintain the play list in media players in order to
add and remove the songs from the play-list.
• Queues are used in operating systems for handling interrupts.
Basic Operations

• The most fundamental operations in the queue


ADT include: enqueue(), dequeue(), peek(),
isFull(), isEmpty(). These are all built-in
operations to carry out data manipulation and to
check the status of the queue.
• Queue uses two pointers − front and rear. The
front pointer accesses the data from the front
end (helping in enqueueing) while the rear
pointer accesses data from the rear end (helping
in dequeuing).
Insertion operation: enqueue()

• The enqueue() is a data manipulation operation that is used


to insert elements into the stack. The following algorithm
describes the enqueue() operation in a simpler way.
Deletion Operation: dequeue()

• The dequeue() is a data manipulation operation


that is used to remove elements from the stack.
The following algorithm describes the dequeue()
operation in a simpler way.
The peek() Operation

• The peek() is an operation which is used to


retrieve the frontmost element in the queue,
without deleting it. This operation is used to
check the status of the queue with the help of
the pointer.
The isFull() Operation

• The isFull() operation verifies whether the


stack is full.
The isEmpty() operation

• The isEmpty() operation verifies whether the


stack is empty. This operation is used to check
the status of the stack with the help of top
pointer.
Implementation of Queue
Different ways to sort a Queue

• Method 1 : Using auxiliary array


• Method 2 : O(1) space required
• Method 3 : Using recursion
• Method 4 : Using stack
Method 1 : Using auxiliary array

• We use an auxiliary array to store all the elements of


the queue. We then sort the array and put the sorted
elements back into the queue.
• Algorithm:
• The steps to sort a queue using auxiliary array are:
• Create an auxiliary array(static/dynamic).
• Remove all the elements from the queue and put them
into the array.
• Sort the array.
• Put elements of the sorted array back into the queue.
Method 2 : O(1) space required

• We maintain the sorted queue at the end of the queue. For each of the n iterations, we find the
minimum element from the unsorted queue. We store it's value as well as it's index. Then, we
remove minIndex - 1 elements from the queue and p insert them back at the end of the queue. We
pop the minimum element and store it in a variable. Next, we again remove the elements occuring
after the minimum element (elements at indices minIndex+1 to n) and push them at the end f the
queue. The detailed algorithm is discusssed below.
• Algorithm
• The steps to sort a queue using O(1) space are:
Do this N times:
1. Search for the minimum element in the unsorted part of the queue. Store it's value and the
index.
2. Remove the elements occuring before the minimum element from the front of the queue and
insert them at the end of the queue.
3. Once the index of the minimum element is reached, pop the minimum element ans store it in a
variable.
4. Next, remove the elements occuring after the minimum element from the front of the queue
and insert them at the end of the queue.
5. Finally, insert the minimum element (from 3) into the end of the queue.
• For searching the element in the queue int Step 1, we traverse the queue and find the minimum
element. After a complete traversal, the queue comes to the same state as it was before the
traversal started. Hence, Step 1 does not effectively change the queue in any way.
Method 3 : Using recursion

• We can also use recursion to sort a queue. We first remove the


element at the front of the queue. Then, we make a recursive call
for the remaining queue. We use recursion in such a way that after
the recursive call returns we have a sorted queue in the ascending
order (smallest element at the front of the queue).
• Once this sorted queue is received, we insert our current element
we need to place the current element at it's correct position. To do
this, we first pop all the elements which are smaller than the
current element and insert then at the end of the queue. Once we
find an element equal to or greater than the current element, we
insert the current element at the end of the queue.
• Next, we pop the remaining elements (equal or greater than the
current element) and insert them at the end of the queue. This will
give us a sorted queue.
Algorithm

• The steps to sort a queue using recursion are:


• If the q has no element or has only 1 element, return.
• Pop the current element present at the front of the queue.
• Now, use recursion to sort the remaining queue.
• The recursive call returns a sorted queue (in ascending order),
which does not contain the current element.
• We pop the elements smaller than the current element, and insert
them at the end of the queue.
• Once we encounter an element greater or equal to the current
element at the front of the queue, we push the current element at
the end of the queue.
• Now, pop the elements greater than/equal to the current element
and insert them at the end of the queue until an element smaller
than the current element is found.
Method 4 : Using stack

• Idea is to maintain the sorted elements of the queue in the auxiliary stack. We also use an extra
queue for maintaining the order of the sorted elements in the stack when a new element is to be
pushed in the stack.

• Algorithm
• The steps to sort a queue using Stack are:
• Create an auxiliary stack and an auxiliary queue.
• If the stack is empty, push the element in the stack.
• If the next element at the front of the queue is greater than the top of the stack, push it on the
stack.
• Else, pop the elements out of the stack until a smaller or equal element is found at the top of the
stack.
• The popped elements in step 4, must be pushed into the auxiliary queue and once a smaller/equal
element is found, push the current element and empty the auxiliary queue on the stack.
• Continue until the stack size becomes equal to the size of the input queue and he input queue
becomes empty.
• Now transfer all the elements from the stack to the queue. The resulting queue will have the
elements in descending order.
Type of Queues
• Simple Queue or Linear Queue
• Circular Queue
• Priority Queue
• Double Ended Queue (or Deque)
Simple Queue or Linear Queue

• In Linear Queue, an insertion takes place from one end


while the deletion occurs from another end. The end at
which the insertion takes place is known as the rear end,
and the end at which the deletion takes place is known as
front end. It strictly follows the FIFO rule.

• The major drawback of using a linear Queue is that


insertion is done only from the rear end. If the first three
elements are deleted from the Queue, we cannot insert
more elements even though the space is available in a
Linear Queue. In this case, the linear Queue shows the
overflow condition as the rear is pointing to the last
element of the Queue.
Simple Queue or Linear Queue
Circular Queue

• In Circular Queue, all the nodes are represented as


circular. It is similar to the linear Queue except that the
last element of the queue is connected to the first
element. It is also known as Ring Buffer, as all the ends
are connected to another end.

• The drawback that occurs in a linear queue is


overcome by using the circular queue. If the empty
space is available in a circular queue, the new element
can be added in an empty space by simply
incrementing the value of rear. The main advantage of
using the circular queue is better memory utilization.
Circular Queue
Priority Queue
• It is a special type of queue in which the elements are
arranged based on the priority. It is a special type of
queue data structure in which every element has a
priority associated with it. Suppose some elements
occur with the same priority, they will be arranged
according to the FIFO principle.

• Insertion in priority queue takes place based on the


arrival, while deletion in the priority queue occurs
based on the priority. Priority queue is mainly used to
implement the CPU scheduling algorithms.
Priority Queue
Types of priority queue
• There are two types of priority queue that are discussed as
follows -
• Ascending priority queue - In ascending priority queue,
elements can be inserted in arbitrary order, but only
smallest can be deleted first. Suppose an array with
elements 7, 5, and 3 in the same order, so, insertion can be
done with the same sequence, but the order of deleting
the elements is 3, 5, 7.
• Descending priority queue - In descending priority queue,
elements can be inserted in arbitrary order, but only the
largest element can be deleted first. Suppose an array with
elements 7, 3, and 5 in the same order, so, insertion can be
done with the same sequence, but the order of deleting
the elements is 7, 5, 3.
Deque (or, Double Ended Queue)

• In Deque or Double Ended Queue, insertion and deletion can be


done from both ends of the queue either from the front or rear.
• It means that we can insert and delete elements from both front
and rear ends of the queue. Deque can be used as a palindrome
checker means that if we read the string from both ends, then the
string would be the same.
• Deque can be used both as stack and queue as it allows the
insertion and deletion operations on both ends.
• Deque can be considered as stack because stack follows the LIFO
(Last In First Out) principle in which insertion and deletion both can
be performed only from one end.
• And in deque, it is possible to perform both insertion and deletion
from one end, and Deque does not follow the FIFO principle.
Deque (or, Double Ended Queue)
Ways to implement the queue

• There are two ways of implementing the


Queue:
• Implementation using array: The sequential
allocation in a Queue can be implemented
using an array.
• Implementation using Linked list: The linked
list allocation in a Queue can be implemented
using a linked list.
Prefix, Infix, Postfix Notations.

You might also like