INTRODUCTION TO DATA STRUCTURE
In computer science, a data structure is a way of organizing and storing data in a
computer program so that it can be accessed and used efficiently. Data structures provide a
means of managing large amounts of data, enabling efficient searching, sorting, insertion,
and deletion of data.
Classification/Types of Data Structures:
Data structures can be classified into two main types: primitive data structures and nonprimitive data structures.
Primitive data structures: These are the most basic data structures and are usually built into
programming languages. Examples include:
Integer
Float
Character
Boolean
Double
Void
Non-primitive data structures: These are complex data structures that are built using
primitive data types. Non-primitive data structures can be further categorized into the
following types:
Arrays: A collection of elements of the same data type, stored in contiguous memory
locations.
Linked lists: A collection of elements that are connected by links or pointers.
Stacks: A collection of elements that follow the Last-In-First-Out (LIFO) principle.
Queues: A collection of elements that follow the First-In-First-Out (FIFO) principle.
Trees: A hierarchical data structure consisting of nodes connected by edges.
Graphs: A non-linear data structure consisting of nodes and edges.
Hash tables: A data structure that stores data in an associative manner using a hash
function.
Heaps: A specialized tree-based data structure that satisfies the heap property.
Tries: A tree-like data structure used to store associative arrays where the keys are strings.
Sets: A collection of unique elements.
Maps: An abstract data type that stores key-value pairs.
The choice of data structure depends on the problem to be solved and the operations to be
performed on the data. Different data structures have different strengths and weaknesses
and are suitable for different scenarios. Understanding the different types of data structures
and their characteristics is important for efficient algorithm design and implementation.
1.
Linear Data Structure
2.
Non-Linear Data Structure.
Linear Data Structure:
A linear data structure is a type of data structure in which data elements are
arranged in a sequential order, and each element has a unique predecessor and
successor, except for the first and last elements. Linear data structures are onedimensional and can be traversed sequentially from the first to the last element.
Elements are arranged in one dimension ,also known as linear dimension.
Example: lists, stack, queue, etc.
Non-Linear Data Structure
A Non-linear data structure is a type of data structure in which data elements
are not arranged in a sequential order, and each element may have one or more
predecessors and successors. Non-linear data structures can represent complex
relationships between data elements, such as hierarchies, networks, and graphs.
Elements are arranged in one-many, many-one and many-many dimensions.
Example: tree, graph, table, etc.
Most Popular Data Structures:
1. Array: An array is a collection of data 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).
2. Linked Lists: Like arrays, Linked List is a linear data structure. Unlike arrays, linked list
elements are not stored at a contiguous location; the elements are linked using pointers.
3. 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). In stack, all insertion and deletion are permitted at only one end of the list.
Mainly the following three basic operations are performed in the stack:
Initialize: Make a stack empty.
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 the stack.
isEmpty: Returns true if the stack is empty, else false.
4. Queue: Like Stack, Queue is a linear structure which follows a particular order in which
the operations are performed. The order is First In First Out (FIFO). In the queue, items are
inserted at one end and deleted from the other end. A good example of the 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.
Mainly the following four basic operations are performed on queue:
Enqueue: Adds an item to the queue. If the queue is full, then it is said to be an
Overflow condition.
Dequeue: Removes an item from the queue. The items are popped in the same
order in which they are pushed. If the queue is empty, then it is said to be an
Underflow condition.
Front: Get the front item from the queue.
Rear: Get the last item from the queue.
5. Binary Tree: Unlike Arrays, Linked Lists, Stack and queues, which are linear data
structures, trees are hierarchical data structures. A binary tree is a tree data structure in
which each node has at most two children, which are referred to as the left child and the
right child. It is implemented mainly using Links.
A Binary Tree is represented by a pointer to the topmost node in the tree. If the tree is
empty, then the value of root is NULL. A Binary Tree node contains the following parts.
1. Data
2. Pointer to left child
3. Pointer to the right child
6. Binary Search Tree: A Binary Search Tree is a Binary Tree following the additional
properties:
The left part of the root node contains keys less than the root node key.
The right part of the root node contains keys greater than the root node key.
There is no duplicate key present in the binary tree.
A Binary tree having the following properties is known as Binary search tree (BST).
7. Heap: A Heap is a special Tree-based data structure in which the tree is a complete
binary tree. Generally, Heaps can be of two types:
Max-Heap: In a Max-Heap the key present at the root node must be greatest
among the keys present at all of its children. The same property must be
recursively true for all sub-trees in that Binary Tree.
Min-Heap: In a Min-Heap the key present at the root node must be minimum
among the keys present at all of its children. The same property must be
recursively true for all sub-trees in that Binary Tree.
8. Hashing Data Structure: Hashing is an important Data Structure which is designed to
use a special function called the Hash function which is used to map a given value with a
particular key for faster access of elements. The efficiency of mapping depends on the
efficiency of the hash function used.
Let a hash function H(x) maps the value x at the index x%10 in an Array. For example, if
the list of values is [11, 12, 13, 14, 15] it will be stored at positions {1, 2, 3, 4, 5} in the
array or Hash table respectively.
9. Matrix: A matrix represents a collection of numbers arranged in an order of rows and
columns. It is necessary to enclose the elements of a matrix in parentheses or brackets.
A matrix with 9 elements is shown below.
10. Trie: Trie is an efficient information reTrieval data structure. Using Trie, search
complexities can be brought to an optimal limit (key length). If we store keys in the binary
search tree, a well-balanced BST will need time proportional to M * log N, where M is
maximum string length and N is the number of keys in the tree. Using Trie, we can search
the key in O(M) time. However, the penalty is on Trie storage requirements.
Applications of Data Structures:
Arrays: Arrays are used to store a collection of homogeneous elements in
contiguous memory locations. They are commonly used to implement other data
structures, such as stacks and queues, and to represent matrices and tables.
V
Linked lists: Linked lists are used to store a collection of heterogeneous
elements with dynamic memory allocation. They are commonly used to
implement stacks, queues, and hash tables.
Trees: Trees are used to represent hierarchical data structures, such as file
systems, organization charts, and network topologies. Binary search trees are
commonly used to implement dictionaries and symbol tables.
Graphs: Graphs are used to represent complex relationships between data
elements, such as social networks, transportation networks, and computer
networks. They are commonly used to implement shortest path algorithms and
graph traversal algorithms.
Hash tables: Hash tables are used to implement associative arrays, which store
key-value pairs. They provide fast access to data elements based on their keys.
Stacks: Stacks are used to store a collection of elements in a last-in-first-out
(LIFO) order. They are commonly used to implement undo-redo functionality,
recursive function calls, and expression evaluation.
Queues: Queues are used to store a collection of elements in a first-in-first-out
(FIFO) order. They are commonly used to implement waiting lines, message
queues, and job scheduling.
ARRAY
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).
Two Type of array:
1). Single/One Dimensional array
2). Multi-Dimensional Array
One Dimensional Array
Declaration of one dimensional array:
An array can be declared with the bracket punctuators [ ], as shown in the below syntax:
Data_Type Array_Name[Number_Of_Elements]
The below example shows a declaration of an array having the capacity to hold 50 elements
of type integers and the name of that array is arr :
int arr[50];
Initializing the array:
We can initialize an array in C by assigning value to each index one by one or by using a
single statement as follows −
Example 1 :
Assign one value each time to the array
int arr[50];
arr[0]=12;
arr[1]= 43;
arr[2] = 14;
.
.
.
.
.
arr[49] = 54;
Example 2:
Using a single statement
int arr[5] = {10,32,11,45,38};
Multidimensional Arrays
We can say a Multidimensional array is an array of arrays. Two Dimensional arrays is also a
multidimensional array. In a Multi-Dimensional array, elements of an array are arranged in
the form of rows and columns.
Multidimensional array stores elements in tabular form which is also known as in row-major
order or column-major order.
Declaration of Multi-dimensional Array
data_type array_name[size1][size2]….[sizeN];
data_type: It defines the type of data that can be held by an array. Here data_type can be int,
char, float. etc.
array_name: Name of the array
size1, size2,… ,sizeN: Sizes of the dimensions
Pictorial representation of a multidimensional array
number_of_arrays: number of arrays which flow in the z-axis
rows: number of the rows in the y-axis
columns: number of the columns flow in the x-axis
Two-dimensional array
int arr1[10][20];
SORTING
Sorting refers to rearrangement of a given array or list of elements according to a
comparison operator on the elements. The comparison operator is used to decide the
new order of elements in the respective data structure.
Some of the most common sorting algorithms are:
Below are some of the most common sorting algorithms:
1. Selection sort
Selection sort is another sorting technique in which we find the minimum element in every
iteration and place it in the array beginning from the first index. Thus, a selection sort also
gets divided into a sorted and unsorted subarray.
Working of Selection Sort algorithm:
Lets consider the following array as an example: arr[] = {64, 25, 12, 22, 11}
First pass:
For the first position in the sorted array, the whole array is traversed from index 0 to 4
sequentially. The first position where 64 is stored presently, after traversing whole array it
is clear that 11 is the lowest value.
64
25
12
22
11
Thus, replace 64 with 11. After one iteration 11, which happens to be the least value in the
array, tends to appear in the first position of the sorted list.
11
25
12
22
64
Second Pass:
For the second position, where 25 is present, again traverse the rest of the array in a
sequential manner.
11
25
12
22
64
After traversing, we found that 12 is the second lowest value in the array and it should
appear at the second place in the array, thus swap these values.
11
12
25
22
64
Third Pass:
Now, for third place, where 25 is present again traverse the rest of the array and find the
third least value present in the array.
11
12
25
22
64
While traversing, 22 came out to be the third least value and it should appear at the third
place in the array, thus swap 22 with element present at third position.
11
12
22
25
64
Fourth pass:
Similarly, for fourth position traverse the rest of the array and find the fourth least element
in the array
As 25 is the 4th lowest value hence, it will place at the fourth position.
11
12
22
25
64
Fifth Pass:
At last the largest value present in the array automatically get placed at the last position in
the array
The resulted array is the sorted array.
11
12
22
25
64
2. Bubble sort
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the
adjacent elements if they are in the wrong order. This algorithm is not suitable for large
data sets as its average and worst-case time complexity is quite high.
Working of Bubble Sort algorithm:
Lets consider the following array as an example: arr[] = {5, 1, 4, 2, 8}
First Pass:
Bubble sort starts with very first two elements, comparing them to check which one is
greater.
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps
since 5 > 1.
( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5),
algorithm does not swap them.
Second Pass:
Now, during second iteration it should look like this:
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Third Pass:
Now, the array is already sorted, but our algorithm does not know if it is completed.
The algorithm needs one whole pass without any swap to know it is sorted.
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Illustration:
Illustration of Bubble Sort
3. Insertion Sort
Insertion sort is a simple sorting algorithm that works similarly to the way you sort playing
cards in your hands. The array is virtually split into a sorted and an unsorted part. Values
from the unsorted part are picked and placed at the correct position in the sorted part.
Working of Insertion Sort algorithm:
Consider an example: arr[]: {12, 11, 13, 5, 6}
12
11
13
5
6
First Pass:
Initially, the first two elements of the array are compared in insertion sort.
12
11
11
13
5
6
Here, 12 is greater than 11 hence they are not in the ascending order and 12 is
not at its correct position. Thus, swap 11 and 12.
So, for now 11 is stored in a sorted sub-array.
12
13
5
6
Second Pass:
Now, move to the next two elements and compare them
11
12
13
5
6
Here, 13 is greater than 12, thus both elements seems to be in ascending order,
hence, no swapping will occur. 12 also stored in a sorted sub-array along with
11
Third Pass:
Now, two elements are present in the sorted sub-array which are 11 and 12
Moving forward to the next two elements which are 13 and 5
11
12
13
12
5
5
5
13
6
After swapping, elements 12 and 5 are not sorted, thus swap again
11
6
Both 5 and 13 are not present at their correct place so swap them
11
5
12
13
6
Here, again 11 and 5 are not sorted, hence swap again
11
12
13
6
here, it is at its correct position
Fourth Pass:
Now, the elements which are present in the sorted sub-array are 5, 11 and 12
Moving to the next two elements 13 and 6
5
11
5
5
5
6
12
6
13
Now, 6 is smaller than 12, hence, swap again
11
13
Clearly, they are not sorted, thus perform swap between both
11
12
6
12
13
Here, also swapping makes 11 and 6 unsorted hence, swap again
6
11
12
13
Finally, the array is completely sorted.
Illustrations:
4. Merge Sort
The Merge Sort algorithm is a sorting algorithm that is based on the Divide and
Conquers paradigm. In this algorithm, the array is initially divided into two equal halves
and then they are combined in a sorted manner.
Let’s see how Merge Sort uses Divide and Conquer:
The merge sort algorithm is an implementation of the divide and conquers technique. Thus,
it gets completed in three steps:
1. Divide: In this step, the array/list divides itself recursively into sub-arrays until
the base case is reached.
2. Conquer: Here, the sub-arrays are sorted using recursion.
3. Combine: This step makes use of the merge( ) function to combine the subarrays into the final sorted array.
Working of Merge Sort algorithm:
To know the functioning of merge sort, lets consider an array arr[] = {38, 27, 43, 3, 9, 82,
10}
At first, check if the left index of array is less than the right index, if yes then calculate its
mid point
Now, as we already know that merge sort first divides the whole array iteratively into equal
halves, unless the atomic values are achieved.
Here, we see that an array of 7 items is divided into two arrays of size 4 and 3 respectively.
Now, again find that is left index is less than the right index for both arrays, if found yes,
then again calculate mid points for both the arrays.
Now, further divide these two arrays into further halves, until the atomic units of the array
is reached and further division is not possible.
After dividing the array into smallest units, start merging the elements again based on
comparison of size of elements
Firstly, compare the element for each list and then combine them into another list in a
sorted manner.
After the final merging, the list looks like this:
5. Quick sort
Quicksort is a sorting algorithm based on the divide and conquer approach where an array
is divided into subarrays by selecting a pivot element (element selected from the array).
1. While dividing the array, the pivot element should be positioned in such a way
that elements less than the pivot are kept on the left side, and elements greater
than the pivot is on the right side of the pivot.
2. The left and right subarrays are also divided using the same approach. This
process continues until each subarray contains a single element.
3. At this point, elements are already sorted. Finally, elements are combined to
form a sorted array.
Working of Quick Sort algorithm:
To know the functioning of Quick sort, let’s consider an array arr[] = {10, 80, 30, 90, 40,
50, 70}
Indexes: 0 1 2 3 4 5 6
low = 0, high = 6, pivot = arr[h] = 70
Initialize index of smaller element, i = -1
Step1
Traverse elements from j = low to high-1
j = 0: Since arr[j] <= pivot, do i++ and swap(arr[i], arr[j])
i=0
arr[] = {10, 80, 30, 90, 40, 50, 70} // No change as i and j are same
j = 1: Since arr[j] > pivot, do nothing
Step2
j = 2 : Since arr[j] <= pivot, do i++ and swap(arr[i], arr[j])
i=1
arr[] = {10, 30, 80, 90, 40, 50, 70} // We swap 80 and 30
Step3
j = 3 : Since arr[j] > pivot, do nothing // No change in i and arr[]
j = 4 : Since arr[j] <= pivot, do i++ and swap(arr[i], arr[j])
i=2
arr[] = {10, 30, 40, 90, 80, 50, 70} // 80 and 40 Swapped
Step 4
j = 5 : Since arr[j] <= pivot, do i++ and swap arr[i] with arr[j]
i=3
arr[] = {10, 30, 40, 50, 80, 90, 70} // 90 and 50 Swapped
Step 5
We come out of loop because j is now equal to high-1.
Finally we place pivot at correct position by swapping arr[i+1] and arr[high]
(or pivot)
arr[] = {10, 30, 40, 50, 70, 90, 80} // 80 and 70 Swapped
Step 6
Now 70 is at its correct place. All elements smaller than 70 are before it and all
elements greater than 70 are after it.
Since quick sort is a recursive function, we call the partition function again at
left and right partitions
Step 7
Again call function at right part and swap 80 and 90
Step8
SEARCHING :
Linear Search is defined as a sequential search algorithm that starts at one end and
goes through each element of a list until the desired element is found, otherwise the
search continues till the end of the data set.
Linear Search Algorithm
How Does Linear Search Algorithm Work?
In Linear Search Algorithm,
Every element is considered as a potential match for the key and checked
for the same.
If any element is found equal to the key, the search is successful and the
index of that element is returned.
If no element is found equal to the key, the search yields “No match found”.
For example: Consider the array arr[] = {10, 50, 30, 70, 80, 20, 90, 40} and key = 30
Step 1: Start from the first element (index 0) and compare key with each element
(arr[i]).
Comparing key with first element arr[0]. SInce not equal, the iterator moves to the
next element as a potential match.
Comparing key with next element arr[1]. SInce not equal, the iterator moves to the
next element as a potential match.
Step 2: Now when comparing arr[2] with key, the value matches. So the Linear Search
Algorithm will yield a successful message and return the index of the element when
key is found (here 2).
Complexity Analysis of Linear Search:
Time Complexity:
Best Case: In the best case, the key might be present at the first index. So the
best case complexity is O(1)
Worst Case: In the worst case, the key might be present at the last index i.e.,
opposite to the end from which the search has started in the list. So the worstcase complexity is O(N) where N is the size of the list.
Average Case: O(N)
Auxiliary Space: O(1) as except for the variable to iterate through the list, no other
variable is used.
Advantages of Linear Search:
Linear search can be used irrespective of whether the array is sorted or not. It
can be used on arrays of any data type.
Does not require any additional memory.
It is a well-suited algorithm for small datasets.
Drawbacks of Linear Search:
Linear search has a time complexity of O(N), which in turn makes it slow for
large datasets.
Not suitable for large arrays.
*BINARY SEARCH
Binary Search is defined as a searching algorithm used in a sorted array
by repeatedly dividing the search interval in half. The idea of binary search is to
use the information that the array is sorted and reduce the time complexity to O(log
N).
In this algorithm,
Divide the search space into two halves by finding the middle index
“mid”.
Compare the middle element of the search space with the key.
If the key is found at middle element, the process is terminated.
If the key is not found at middle element, choose which half will be used as
the next search space.
If the key is smaller than the middle element, then the left side is used
for next search.
If the key is larger than the middle element, then the right side is used
for next search.
This process is continued until the key is found or the total search space is
exhausted.
How the binary search Works :
Consider an array arr[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91}, and the target = 23.
First Step: Calculate the mid and compare the mid element with the key. If the key is
less than mid element, move to left and if it is greater than the mid then move search
space to the right.
Key (i.e., 23) is greater than current mid element (i.e., 16). The search
space moves to the right.
Key is less than the current mid 56. The search space moves to the left.
Second Step: If the key matches the value of the mid element, the element is found
and stop search.
Complexity Analysis of Binary Search:
Time Complexity:
Best Case: O(1)
Average Case: O(log N)
Worst Case: O(log N)
Auxiliary Space: O(1), If the recursive call stack is considered then the auxiliary
space will be O(logN).
Advantages of Binary Search:
Binary search is faster than linear search, especially for large arrays.
More efficient than other searching algorithms with a similar time complexity,
such as interpolation search or exponential search.
Binary search is well-suited for searching large datasets that are stored in external
memory, such as on a hard drive or in the cloud.
Drawbacks of Binary Search:
The array should be sorted.
Binary search requires that the data structure being searched be stored in
contiguous memory locations.
Binary search requires that the elements of the array be comparable, meaning that
they must be able to be ordered.
Applications of Binary Search:
Binary search can be used as a building block for more complex algorithms used
in machine learning, such as algorithms for training neural networks or finding the
optimal hyperparameters for a model.
It can be used for searching in computer graphics such as algorithms for ray
tracing or texture mapping.
It can be used for searching a database.
Stack
What is Stack?
Stack is a linear data structure that 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). 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.
Stack Data Structure
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.
Basic Operations on Stack
In order to make manipulations in a stack, there are certain operations provided to us.
push() to insert an element into the stack
pop() to remove an element from the stack
top() Returns the top element of the stack.
isEmpty() returns true if stack is empty else false.
size() returns the size of stack.
Stack
Push:
Adds an item to the stack. If the stack is full, then it is said to be an Overflow
condition.
Algorithm for push:
begin
if stack is full
return
endif
else
increment top
stack[top] assign value
end else
end procedure
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.
Algorithm for pop:
begin
if stack is empty
return
endif
else
store value of stack[top]
decrement top
return value
end else
end procedure
Top:
Returns the top element of the stack.
Algorithm for Top:
begin
return stack[top]
end procedure
isEmpty:
Returns true if the stack is empty, else false.
Algorithm for isEmpty:
begin
if top < 1
return true
else
return false
end procedure
APPLICATION OF STACK
Convert Infix expression to Postfix expression
Infix expression: The expression of the form “a operator b” (a + b) i.e., when an
operator is in-between every pair of operands.
Postfix expression: The expression of the form “a b operator” (ab+) i.e., When
every pair of operands is followed by an operator.
Input: A + B * C + D
Output: ABC*+D+
How to convert an Infix expression to a Postfix expression?
To convert infix expression to postfix expression, use the stack data structure. Scan
the infix expression from left to right. Whenever we get an operand, add it to the
postfix expression and if we get an operator or parenthesis add it to the stack by
maintaining their precedence.
Below are the steps to implement the above idea:
1. Scan the infix expression from left to right.
2. If the scanned character is an operand, put it in the postfix expression.
3. Otherwise, do the following
If the precedence and associativity of the scanned operator are
greater than the precedence and associativity of the operator in
the stack [or the stack is empty or the stack contains a ‘(‘ ], then
push it in the stack. [‘^‘ operator is right associative and other
operators like ‘+‘,’–‘,’*‘ and ‘/‘ are left-associative].
Check especially for a condition when the operator at
the top of the stack and the scanned operator both are
‘^‘. In this condition, the precedence of the scanned
operator is higher due to its right associativity. So it
will be pushed into the operator stack.
In all the other cases when the top of the operator
stack is the same as the scanned operator, then pop the
operator from the stack because of left associativity
due to which the scanned operator has less
precedence.
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.)
4. If the scanned character is a ‘(‘, push it to the stack.
5. If the scanned character is a ‘)’, pop the stack and output it until a ‘(‘ is
encountered, and discard both the parenthesis.
6. Repeat steps 2-5 until the infix expression is scanned.
7. Once the scanning is over, Pop the stack and add the operators in the
postfix expression until it is not empty.
8. Finally, print the postfix expression.
Illustration:
Follow the below illustration for a better understanding
Consider the infix expression exp = “a+b*c+d”
and the infix expression is scanned using the iterator i, which is initialized as i = 0.
1st Step: Here i = 0 and exp[i] = ‘a’ i.e., an operand. So add this in the postfix
expression. Therefore, postfix = “a”.
Add ‘a’ in the postfix
2nd Step: Here i = 1 and exp[i] = ‘+’ i.e., an operator. Push this into the
stack. postfix = “a” and stack = {+}.
Push ‘+’ in the stack
3rd Step: Now i = 2 and exp[i] = ‘b’ i.e., an operand. So add this in the postfix
expression. postfix = “ab” and stack = {+}.
Add ‘b’ in the postfix
4th Step: Now i = 3 and exp[i] = ‘*’ i.e., an operator. Push this into the
stack. postfix = “ab” and stack = {+, *}.
Push ‘*’ in the stack
5th Step: Now i = 4 and exp[i] = ‘c’ i.e., an operand. Add this in the postfix
expression. postfix = “abc” and stack = {+, *}.
Add ‘c’ in the postfix
6th Step: Now i = 5 and exp[i] = ‘+’ i.e., an operator. The topmost element of the
stack has higher precedence. So pop until the stack becomes empty or the top
element has less precedence. ‘*’ is popped and added in postfix. So postfix =
“abc*” and stack = {+}.
Pop ‘*’ and add in postfix
Now top element is ‘+‘ that also doesn’t have less precedence. Pop it. postfix =
“abc*+”.
Pop ‘+’ and add it in postfix
Now stack is empty. So push ‘+’ in the stack. stack = {+}.
Push ‘+’ in the stack
7th Step: Now i = 6 and exp[i] = ‘d’ i.e., an operand. Add this in the postfix
expression. postfix = “abc*+d”.
Add ‘d’ in the postfix
Final Step: Now no element is left. So empty the stack and add it in the postfix
expression. postfix = “abc*+d+”.
Pop ‘+’ and add it in postfix
Below is the implementation of the above algorithm:
Infix to Prefix conversion
Infix: An expression is called the Infix expression if the operator appears in between
the operands in the expression. Simply of the form (operand1 operator operand2).
Example : (A+B) * (C-D)
Prefix: An expression is called the prefix expression if the operator appears in the
expression before the operands. Simply of the form (operator operand1 operand2).
Example : *+AB-CD (Infix : (A+B) * (C-D) )
Given an Infix expression, convert it into a Prefix expression using two stacks.
Examples:
Input : A * B + C / D
Output : + * A B/ C D
Input : (A - B/C) * (A/K-L)
Output : *-A/BC-/AKL
ALGORITHM :
1. Traverse the infix expression and check if given character is an operator or
an operand.
2. If it is an operand, then push it into operand stack.
3. If it is an operator, then check if priority of current operator is greater than
or less than or equal to the operator at top of the stack. If priority is
greater, then push operator into operator stack. Otherwise pop two
operands from operand stack, pop operator from operator stack and push
string operator + operand 2 + operand 1 into operand stack. Keep
popping from both stacks and pushing result into operand stack until
priority of current operator is less than or equal to operator at top of the
operator stack.
4. If current character is ‘(‘, then push it into operator stack.
5. If current character is ‘)’, then check if top of operator stack is opening
bracket or not. If not pop two operands from operand stack, pop operator
from operator stack and push string operator + operand 2 + operand
1 into operand stack. Keep popping from both stacks and pushing result
into operand stack until top of operator stack is an opening bracket.
6. The final prefix expression is present at top of operand stack.
QUEUE :
What is Queue?
A queue is 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. The element which is first
pushed into the order, the delete operation is first performed on that.
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.
FIFO property of queue
Characteristics of Queue:
Queue can handle multiple data.
We can access both ends.
They are fast and flexible.
Queue Representation:
1. Array Representation of Queue:
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.
Basic Operations for Queue in Data Structure:
Some of the basic operations for Queue in Data Structure are:
1. Enqueue() – Adds (or stores) an element to the end of the queue..
2. Dequeue() – Removal of elements from the queue.
3. Peek() or front()- Acquires the data element available at the front node of
the queue without deleting it.
4. rear() – This operation returns the element at the rear end without
removing it.
5. isFull() – Validates if the queue is full.
6. isNull() – Checks if the queue is empty.
There are a few supporting operations (auxiliary operations):
1. Enqueue():
Enqueue() operation in Queue adds (or stores) an element to the end of the queue.
The following steps should be taken to enqueue (insert) data into a queue:
Step 1: Check if the queue is full.
Step 2: If the queue is full, return overflow error and exit.
Step 3: If the queue is not full, increment the rear pointer to point to the
next empty space.
Step 4: Add the data element to the queue location, where the rear is
pointing.
Step 5: return success.
Enqueue representation
2. Dequeue():
Removes (or access) the first element from the queue.
The following steps are taken to perform the dequeue operation:
Step 1: Check if the queue is empty.
Step 2: If the queue is empty, return the underflow error and exit.
Step 3: If the queue is not empty, access the data where the front is
pointing.
Step 4: Increment the front pointer to point to the next available data
element.
Step 5: The Return success.
. front():
This operation returns the element at the front end without removing it.
4. rear():
This operation returns the element at the rear end without removing it.
5. isEmpty():
This operation returns a boolean value that indicates whether the queue is empty or
not.
6.isFull():
This operation returns a boolean value that indicates whether the queue is full or not.
What is a Circular Queue?
A Circular Queue is an extended version of a normal queue where the last element of the
queue is connected to the first element of the queue forming a circle.
The operations are performed based on FIFO (First In First Out) principle. It is also
called ‘Ring Buffer’.
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.
Operations on Circular Queue:
Front: Get the front item from the queue.
Rear: Get the last item from the 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 the rear
position.
Check whether the queue is full – [i.e., the rear end is in just before
the front end in a circular manner].
If it is full then display Queue is full.
If the queue is not full then, insert an element at the end
of the queue.
deQueue() This function is used to delete an element from the circular queue. In
a circular queue, the element is always deleted from the front position.
Check whether the queue is Empty.
If it is empty then display Queue is empty.
If the queue is not empty, then get the last element and
remove it from the queue.
Illustration of Circular Queue Operations:
Follow the below image for a better understanding of the enqueue and dequeue operations.
Working of Circular queue operations
How to Implement a Circular Queue?
A circular queue can be implemented using two data structures:
Array
Linked List
Here we have shown the implementation of a circular queue using an array data structure.
Implement Circular Queue using Array:
1. Initialize an array queue of size n, where n is the maximum number of elements
that the queue can hold.
2. Initialize two variables front and rear to -1.
3. Enqueue: To enqueue an element x into the queue, do the following:
Increment rear by 1.
If rear is equal to n, set rear to 0.
If front is -1, set front to 0.
Set queue[rear] to x.
4. Dequeue: To dequeue an element from the queue, do the following:
Check if the queue is empty by checking if front is -1.
If it is, return an error message indicating that the queue is
empty.
Set x to queue[front].
If front is equal to rear, set front and rear to -1.
Otherwise, increment front by 1 and if front is equal to n,
set front to 0.
Return x.
Applications of Circular Queue:
1. Memory Management: The unused memory locations in the case of ordinary
queues can be utilized in circular queues.
2. Traffic system: In computer controlled traffic system, circular queues are used
to switch on the traffic lights one by one repeatedly as per the time set.
3. CPU Scheduling: Operating systems often maintain a queue of processes that
are ready to execute or that are waiting for a particular event to occur.
0
You can add this document to your study collection(s)
Sign in Available only to authorized usersYou can add this document to your saved list
Sign in Available only to authorized users(For complaints, use another form )