Senior Five Mce MPC Notes Data Structure and Algorithms

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 122

Unit 2.

COMPLEX DATA STRUCTURE


AND
ALGORITHM
Key Unit Competency: To be able to
utilize complex data structure in
algorithm
2.1. Introduction to Data Structures
• Definition: data structure is a way of organizing
and stores data in memory, allowing for efficient
access and manipulation.
• Data structures are essential for designing
algorithms and solving problems in software
development.
 Types of Data Structures:
1.Primitive Data Structures: Basic types like
integers, floats, characters, and booleans.
2.Composite Data Structures: More complex
structures like arrays, lists, stacks, queues, trees,
and graphs, used to handle larger datasets.
2.1.1. Basic types of Data Structures
 We select these data structures based on
which type of operation is required.
2.1.2. Advantages of Data Structures
1.Efficient Storage: Organize data for quick access and minimal
memory use.
2.Algorithm Design: Improve algorithm performance with the
right data structure.
3.Search & Retrieval: Fast searching and retrieving with arrays,
trees, hash tables, etc.
4.Sorting & Ordering: Enable efficient sorting and ordering of
data.
5.Memory Management: Optimize memory usage and reduce
fragmentation.
6.Real-world Use: Essential in databases, file systems, and
network protocols.
7.Code Reusability: Use data structures across different projects.
8.Problem Solving: Simplify solving complex computational
problems.
9.Scalability: Handle growing data efficiently.
10.Easier Debugging: Simplify debugging and maintenance tasks.
2.1.3. Operations on data structure
1.Traversing: Visiting each element to perform tasks
like searching or sorting.
1. Example: Calculating the average of marks by
summing them and dividing by the number of
subjects.
2.Insertion: Adding an element to the data structure
at any position.
3.Deletion: Removing an element from the data
structure. An underflow occurs if it’s empty.
4.Searching: Finding the location of an element. Uses
algorithms like Linear Search or Binary Search.
5.Sorting: Arranging elements in a specific order
using algorithms like insertion sort, bubble sort, etc.
6.Merging: Combining two lists into one larger list.
Application
some questions related to 1. What is a data structure,
the introduction to data and why is it important in
structures and their computer science and
operations: programming?

2. Explain the difference


3. List and briefly describe
between a primitive data
some common primitive
type and a composite data
data types in programming
structure. Provide examples
languages.
of each.

5. What are the basic


4. Define the term
operations that can be
"algorithm." How do data
performed on a data
structures relate to
structure? Explain each of
algorithm design?
them.
Introduction to One-dimensional and Multi-
dimensional Arrays in C++
Learning Objectives
• Understand what arrays are in C++
• Learn how to declare and use one-
dimensional arrays
• Learn how to declare and use multi-
dimensional arrays, including two-
dimensional arrays
• Understand how to access and manipulate
array elements
• Practice through C++ examples and
application exercises
What is an Array?
• Definition: An array is a collection of
elements of the same data type stored at
contiguous memory locations.
• Key Concept: Arrays in C++ are used to
store multiple values in a single variable.
• Example: int numbers[5]; // Declares an array
of 5 integers
2.2.1. Arrays dimensions:
A dimension in an array refers to the direction
in which the array's elements are organized. An
array can have one or more dimensions.
One-dimensional Array
• Syntax: data_type array_name[array_size];
• Example: int arr[10]; // Declares an array of 10
integers
• Accessing Elements: Use indices to access
elements.
• Example: arr[0] = 5;
One-dimensional Array
Example Code:
Multi-dimensional Arrays
• Definition: An array of arrays where each
element is itself an array.
• Common Type: Two-dimensional arrays (2D
arrays)
• Syntax: data_type array_name[rows]
[columns];
• Example: int matrix[3][4]; // 2D array with 3
rows and 4 columns
• Real-world Analogy: Think of it as a table
with rows and columns.
2.2.2. Two dimensional array

Definition
A two dimensional array is a collection of a
fixed number of elements (components) of the
same data type arranged in columns and rows
making two dimensions.
The two dimensional array is also called a
matrix or a table.
The intersection of a column and a row is
called a cell.
The numbering of rows and columns starts by
0.
Demonstration of Columns, rows and indexes

Example: The array a[3][4] is an array of 3 rows and 4 columns. In


matrix representation, it looks like the following:

a[i][j] means that it is an element located at the intersection of row


i and column j. Each element is identified by its row and column
Two dimensional array initialization
Int A[3][4]={A[0][0], A[0][1], A[0][2], A[0][3],
A[1][0], A[1][1], A[1][2], A[1][3], A[2][0], A[2][1],
An example of marks for 3 students in 4 courses. The array will look
A[2][2], A[2][3]};
like this:

If the table is called marks, marks [1][3]=15; where the row position is
1 and the column position is 3.
The expression marks [0] [0] will access the first element of the
matrix marks and marks [2] [3] will access the last row and last
column.
Two-dimensional Array
Example Code:
Higher-dimensional Arrays
• General Form: data_type array_name[size1]
[size2]...[sizeN];
• Example: int cube[3][3][3];
• Note: Higher-dimensional arrays (like 3D
arrays) can be thought of as arrays of 2D
arrays.
Applications of Arrays
• One-dimensional Arrays:
• Storing a list of student marks
• Storing temperature readings
• Two-dimensional Arrays:
• Representing matrices (e.g., in mathematical
calculations)
• Storing data in tabular form (like a
spreadsheet)
C++ Application Exercise (One-
dimensional Array)
• Exercise: Write a C++ program to find the
sum of all elements in a one-dimensional
array.
• Hint: Use a loop to iterate through the array
and sum the elements.
C++ Application Exercise (Two-
dimensional Array)
• Exercise: Write a C++ program to calculate
the transpose of a 3x3 matrix.
• Hint: Use two nested loops to iterate through
the matrix.
Conclusion
• Summary:
• Arrays allow you to store multiple values of
the same type in contiguous memory.
• One-dimensional arrays are like lists, while
two-dimensional arrays are like tables.
• Practice is essential to mastering arrays,
especially when accessing elements.
Syntax to initializing two-dimensional arrays
BEGIN
SET marks=Array[3] [4] of Integer
marks[0][0]=18
marks[0][1]=16
marks[0][2]=14
marks[0][3]=19
marks[1][0]=10
marks[1][1]=20
marks[1][2]=12
marks[1][3]=15
marks[2][0]=15
marks[2][1]=17
marks[2][2]=18
marks[2][3]=16
END
2.2 Array of elements in data structure
.
4. C++ Program to store temperature of two different cities
for a week and display it. The sample out put:
City 1, Day 1 : 32
City 1, Day 2 : 33
Etc…..
2.3. Abstract Data Types (ADT)

• Definition: ADTs are models that describe


how a data structure behaves, without
showing how it's built.
• ADT have two main parts:
• Data: The information stored in the ADT,
hidden from outside access.
• Operations: Actions or functions that can be
done with the data, defining how it is used or
changed.
2.3.2 Importance of abstract data type in data structures
• ADTs are essential for building and using data
structures in programming.
• They make code easier to reuse, maintain, and
understand.
Common ADT examples:
• Lists: Organize and access data (e.g., arrays,
linked lists, stacks).
• Trees: Structure data in a hierarchy (e.g.,
binary trees, B-trees).
• Graphs: Show relationships between data
(e.g., nodes and edges).
• Queues: Manage tasks in a first-in, first-out
(FIFO) order.
2.4 Lists
A list is a popular data structure for storing
data in sequential order. For example, a list of
students, a list of available rooms, a list of
cities, and a list of books can all be stored
using lists.
The operations listed below are typical of
most lists:
 Retrieve an element from a list.
 Insert a new element to a list.
 Delete an element from a list.
 Find how many elements are in a list.
 Find whether an element is in a list.
 Find whether a list is empty.
Difference between Arrays and Lists
• Arrays:
• Fixed in size, stores elements of the same data
type.
• Allocates a fixed memory size at creation.
• Insertion and deletion can be inefficient
(requires shifting elements).
• Lists:
• Flexible in size, can store different data types.
• Dynamically resizes and uses memory more
efficiently.
• Insertion and deletion are efficient (no need to
shift elements).
2.4.1 Linked list
• A Linked List is a linear data structure that
keeps a list of nodes in memory.
• Each node contains data and a pointer to the
next node, forming a chain.
• Unlike arrays, linked list elements are stored
at non-contiguous memory locations and
linked using pointers.
2.4.1 Advantages of Linked Lists
• Dynamic: Memory is allocated only when
needed.
• Easy Insertion/Deletion: Adding or
removing elements is simple.
• Faster Access: Linked Lists reduce access
time compared to some other data structures.
1. Advantages of Linked Lists
2. Extra memory space for a pointer is required with each
element of the list.
3. No element can be accessed randomly; it has to access
each node sequentially.
4. Reverse Traversing is difficult in linked list.
 Disadvantages of Linked Lists
1.Increased Memory Usage: Each element in a linked list
requires extra memory for storing pointers, which can
lead to higher memory consumption compared to arrays.
2.Sequential Access: Elements cannot be accessed
randomly. To find a specific node, the list must be
traversed sequentially from the head to the desired
position.
3.Difficulty in Reverse Traversing: Unlike arrays, which
allow easy backward traversal, linked lists do not support
efficient reverse traversal without additional pointers or
data structures.
2.4.4 Applications of Linked Lists
1.Dynamic Memory Allocation: Efficiently allocate memory
as needed.
2.Data Structures: Implement stacks and queues.
3.Graph Representation: Represent adjacency lists in
graphs.
4.Hash Tables: Handle collisions with chaining.
5.Sparse Matrices: Store non-zero elements efficiently.
6.Undo Functionality: Track actions for reverting changes.
7.Music Playlists: Manage dynamic song lists.
8.Text Editors: Manage lines of text for insertion/deletion.
9.Memory Management: Manage free memory blocks in OS.

 In Linked Lists we don't need to know the size in advance.


Classification of Linked list
Linked list is classified into three types as
shown below:
Single linked lists
Double linked lists
Circular linked list
2.4.5 Single linked lists
A singly linked list is a chain of elements
where each element points to the next one.
Each element is called a Node.
• Node Structure:
• Data: Stores the value of the node.
• Next: Points to the next node in the list.
This structure allows for a dynamic sequence
of elements that can grow and shrink in size.
Cont…
 In a single linked list, the address of the first node is always
stored in a reference node known as “front” (Sometimes it is
also known as “head”).Always next part (reference part) of
the last node must be NULL

The operations we can perform on single linked lists are insertion,


deletion and traversal.
2.4.6 Double linked lists
 In a double linked list, each node contains a data part and
two addresses, one for the previous node and one for the
next node..
 So, we can traverse forward by using next field and can
traverse backward by using previous field.
 Every node in a double linked list contains three fields and
they are shown in the following figure
2.4.7 Circular Linked List
In circular linked list, every node points to its
next node in the sequence but the last node
of the list holds the address of the first node
hence forming a circular chain.
2.5. Queue
 A queue is a linear list in which data can only be inserted at
one end, called the REAR, and deleted from the other end,
called the FRONT.
 These restrictions ensure that the data is processed through
the queue in the order in which it is received.
 In an other words, a queue is a structure in which whatever
goes fist comes out first (first in, first out(FIFO)
structure).
2.5.1 Types of queues

There exist two types of queues:


Linear queue
Circular queue
a. Linear Queue
Queue data structure is a linear data
structure in which the operations are
performed based on FIFO principle
b. Circular 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.
Queue operations

 There are three main operations related to queues.


 Enqueue: the enqueue operation inserts an items at the rear
of the queue
 Dequeue: the dequeue operation deletes the item at the front
of the queue
 Display: show elements in the array
Algorithm for ENQUEUE operation
1. Check if the queue is full or not.
2. If the queue is full, then print overflow error and
exit the program.
3. If the queue is not full, then increment the tail
and add the element.
Algorithm for DEQUEUE operation
1. Check if the queue is empty or not.
2. If the queue is empty, then print underflow error
and exit the program.
3. If the queue is not empty, then print the element
at the head and increment the head.
2.6 Stack
 A stack is a restricted linear list in which all additions and
deletions are made at one end, the top.
 If we insert a series of data items into a stack and then remove
them, the order of the data is reversed.
 Data input as 5, 10, 15, 20, for example would be removed as 20,
15, 10, and 5.
 This reversing attribute is why stacks are known as Last in, First
out (LIFO) data structures.
Operations performed on stacks
The different operations performed on stacks are as follows:
 Push: adds an element to the stack
 Pop: removes an element from the stack
 Peek: display at top element of the stack
Algorithm for push(value) - Inserting value into the
stack operation

Step 1: Check whether stack is FULL. (top


== SIZE-1)
Step 2: If it is FULL, then display “Stack is
FULL!!! Insertion is not possible!!!” and
terminate the function.
Step 3: If it is NOT FULL, then increment top
value by one (top++) and set stack [top] to
value (stack[top] = value).
Algorithm for pop() - Delete a value from the
Stack operation
Step 1: Check whether stack is EMPTY.
(top == -1)
Step 2: If it is EMPTY, then display “Stack
is EMPTY!!! Deletion is not possible!!!’”
and terminate the function.
Step 3: If it is NOT EMPTY, then delete
stack [top] and decrement top value by
one(top-).
2.7 Introduction to Tree
A tree is one data structure that’s quite often
used to represent hierarchical data.
A tree is a Non-linear data structure
Hierarchical arrangement of data
A tree Has components named after natural
trees
 root

 branches

 leaves

Drawn with root at the top


.
Tree
 A tree data structure can be defined as follows.
 In a tree data structure, if we have N number of nodes then we
can have a maximum of N-1 number of links.
 Tree data structure is a collection of data (Node) which is
organized in hierarchical structure and this is a recursive
definition.
2.7.1 Tree Terminology
 In a tree data structure, we use the following terminology:
a. Root
b. Edge
c. Parent
d. Child
e. Siblings
f. Leaf
g. Internal Nodes
h. Degree
i. Level
j. Height
k. Depth
l. Path
m. Sub Tree
a. Root

In a tree data structure, the first node is


called as Root Node. Every tree must have
root node..
b. Edge
In a tree data structure, the connecting link
between any two nodes is called an Edge. In
a tree with ‘N’ number of nodes there will
be a maximum of ‘N-1’ number of edges.
c. Parent

In a tree data structure, the node which is


predecessor of any node is called a PARENT
NODE. In simple words, the node which
has branch from it to any other node is
called as parent node.
d. Child
In a tree data structure, the node which is
descendant of any node is called a CHILD
Node. In a tree, any parent node can have
any number of child nodes. In a tree, all
the nodes except root are child nodes.
f. Leaf

In a tree data structure, the node which does


not have a child is called a LEAF Node. In a
tree data structure, the leaf nodes are also
called a External Nodes or Terminal node.
g. Internal Nodes
 In a tree data structure, the node which has at least one
child is called INTERNAL Node.
 In a tree data structure, nodes other than leaf nodes are
called Internal Nodes.
 The root node is also said to be Internal Node if the tree
has more than one node.
 Internal nodes are also called as ‹Non-Terminal’ nodes.
h. Degree

 In a tree data structure, the total number of children of a


node is called as DEGREE of that Node.
 In simple words, the Degree of a node is total number of
children it has. The highest degree of a node among all the
nodes in a tree is called the ‘Maximum Degree of Tree’
i.Level
In a tree data structure, the root node is said to be at Level
0 and the children of root node are at Level 1 and the
children of the nodes which are at Level 1 will be at Level 2
and so on...
 In simple words, in a tree each step from top to bottom is
called as a Level and the Level count starts with ‘0’ and
incremented by one at each level (Step).
j. Height
 In a tree data structure, the total number of edges from
leaf node to a particular node in the longest path is called
as HEIGHT of that Node.
 In a tree, height of the root node is said to be height of
the tree. In a tree, height of all leaf nodes is ‘0’.
k. Depth
 In a tree data structure, the total number of edges from
root node to a particular node is called DEPTH of that
Node.
 In a tree, the total number of edges from root node to
a leaf node in the longest path is said to be Depth of
the tree. In a tree, depth of the root node is ‘0’.
l. Path
 In a tree data structure, the sequence of Nodes and Edges
from one node to another node is called as PATH between
those two Nodes.
 Length of a Path is total number of nodes in that
path.
 In below example the path A - B - E - J has length 4.
Sibling nodes
Sibling nodes are nodes on the same
hierarchical level under the same parent
node.
m. Sub Tree
In a tree data structure, each child from a node
forms a sub tree recursively.
Every child node will form a sub-tree on its
parent node.
2.7.2 Binary Tree Representations
A binary tree data structure is represented
using two methods. Those methods are as
follows:
Linked List of Binary Tree representation
 Array Representation
a. Linked List of Binary Tree
representation
Consider a Binary Tree T. T will be maintained
in memory by means of a linked list
representation, which uses three parallel
arrays;
INFO, LEFT, and RIGHT pointer variable ROOT
as follows. In Binary Tree, each node N of T
will correspond to a location k such that:
1. LEFT [k] contains the location of the left child of
node N.
2. INFO [k] contains the data at the node N.
3. RIGHT [k] contains the location of right child of
node N.
Representation of a node:

In this representation of binary tree, root will contain the location of the
root R of T. If any one of the sub tree is empty, then the
corresponding pointer will contain the null value if the tree T itself is
empty, the ROOT will contain the null value.
b. Array Representation of Binary Tree
 Let us consider that we have a tree T. let our tree T is
a binary tree that us complete binary tree. Then there
is an efficient way of representing T in the memory
called the sequential representation or array
representation of T. This representation uses only a
linear array TREE as follows:
 The root N of T is stored in TREE [1].
 If a node occupies TREE [k] then its left child is stored
in TREE [2 * k] and its right child is stored into TREE
[2 * k + 1].
Consider the following Tree:

Its sequential representation is as


follow:
Binary Tree Traversals
 When we wanted to display a binary tree, we need to follow
some order in which all the nodes of that binary tree must
be displayed. In any binary tree displaying order of nodes
depends on the traversal method.
 Displaying (or) visiting order of nodes in a binary tree
is called as Binary Tree Traversal.
 There are three types of binary tree traversals.
 In - Order Traversal
 Pre - Order Traversal
 Post - Order Traversal
 Generally, we traverse a tree to search or locate a given
item or key in the tree or to print all the values it contains.
a. In-order Traversal
 In this traversal method, the left sub tree is visited first,
then the root and later the right sub-tree. We should always
remember that every node may represent a sub tree itself.
We start from A, and following in-
order traversal, we move to its left
subtree B. B is also traversed in-
order. The process goes on until all
the nodes are visited. The output of
inorder traversal of this tree will be
D →−B → E → A → F → C → G

Algorithm:
•Step 1 − Recursively traverse left subtree.
•Step 2 − Visit root node.
•Step 3 − Recursively traverse right subtree.
a. In-order Traversal
b. Pre-order Traversal
 In this traversal method, the root node is visited first, then
the left subtree and finally the right subtree.
We start from A, and following pre-
order traversal, we first visit A itself
and then move to its left subtree B. B
is also traversed pre-order. The
process goes on until all the nodes
are visited. The output of pre-order
traversal of this tree will be −
A→B→D→E→C→F→G
Algorithm:
Until all nodes are traversed −
Step 1 − Visit root node.
Step 2 − Recursively traverse left
subtree.
Step 3 − Recursively traverse
right subtree.
b. Pre-order Traversal
c. Post-order Traversal
 In this traversal method, the root node is visited last, hence
the name. First we traverse the left sub tree, then the right
sub tree and finally the root
We node.
start from A, and following Post-
order traversal, we first visit the left
sub tree B. B is also traversed post-
order. The process goes on until all
the nodes are visited. The output of
post-order traversal of this tree will
be −
D→E→B→F→G→C→A
Algorithm:
Until all nodes are traversed −
Step 1 − Recursively traverse left
subtree.
Step 2 − Recursively traverse
right subtree.
Exercises
Binary Search Tree

Binary Search tree exhibits a special


behavior. A node’s left child must have a
value less than its parent’s value and the
node’s right child must have a value greater
than its parent value.
Basic Operations on binary tree
A Binary Search Tree (BST) is a tree in which all
the nodes follow the below-mentioned properties
The left sub-tree of a node has a key less than or
equal to its parent node’s key.
The right sub-tree of a node has a key greater
than to its parent node’s key.
Thus, BST divides all its sub-trees into two
segments; the left sub-tree and the right sub-
tree and can be defined as :
left_subtree (keys) ≤ node (key) ≤ right_subtree
(keys)
Representation
BST is a collection of nodes arranged in a way where they
maintain BST properties. Each node has a key and an
associated value. While searching, the desired key is
compared to the keys in BST and if found, the associated
value is retrieved.
 Following is a pictorial representation of BST

We observe that the root node key (27) has all less-valued keys on
the left sub-tree and the higher valued keys on the right sub-tree
Basic Operations

Following are the basic operations of a tree −


Search − Searches an element in a tree.
Insert − Inserts an element in a tree.
Pre-order Traversal − Traverses a tree in a
pre-order manner.
In-order Traversal − Traverses a tree in an in-
order manner.
Post-order Traversal − Traverses a tree in a
post-order manner.
Searching and sorting using complex data
structure.
Definition
Searching is the process of finding the location
of a given element in a set of elements.
Searching means to find whether a particular
value is present in an array or not. If the value is
present in the array, then searching is said to be
successful and the searching process gives the
location of that value in the array.
There are two simple approaches to searching:
Linear search: This method traverses a list
sequentially to locate the search key.
Binary search: This method works on sorted lists
by progressively making better guesses to find the
location of a search key.
Linear

search Algorithms
Linear search, also known as sequential search, is a
straightforward way to find a value in a list.
1.Start at the Beginning: Begin with the first element
of the array.
2.Compare Each Element: Check each element one by
one to see if it matches the value you are looking for.
3.Find the Value: If you find the value, note its position
in the array.
4.Continue Until Done: Keep searching through all
the elements until you either find the value or reach
the end of the list.
5.Use with Unordered Lists: Linear search is useful
for searching in lists where the elements are not
sorted.
Note:
“a” is an array of the size n.
“n” is the size of the array “a”
“item” is the element to find in the array “a”.
“loc” is the index of an element in the array “a”.

Begin
for i=0 to (n-1) by 1 do
if (a[i] = item) then
set loc=i
Print loc
exit
endif
endfor
end
Linear Search C++ Program
#include<iostream>
using namespace std;
int main()
{
int arr[10], i, num, index;
cout<<"Enter 10 Numbers: ";
for(i=0; i<10; i++)
cin>>arr[i];
cout<<"\nEnter a Number to Search: ";
cin>>num;
for(i=0; i<10; i++)
{
if(arr[i]==num)
{
index = i;
break;
}
}
cout<<"\nFound at Index No."<<index;
cout<<endl;
return 0;
}
Binary Searchsearch is a fast way to find a value in a sorted
Def: Binary
array by repeatedly dividing the search area in half.
1.Start with the Whole Array: Begin with an interval that
includes the entire array.
2.Find the Middle: Look at the middle element of the
current interval.
3.Narrow Down the Search:
1. If the value you are looking for is less than the middle
element, focus on the lower half of the array.
2. If it is greater, focus on the upper half.
4.Repeat: Continue checking the middle element of the
new interval until you either find the value or have no
more elements to check.
Note. This method is also known as the dichotomy
method or bisection method.
The full binary search Algorithm is given down here .
 Binary search (a, n, item, loc)
 Note:
 “a ” is an array of the size n.
 “n” is the size of the array “a”
 “ item ” is the element to find in the array “a”.
 “loc” is the index of the element in the array “a”.

Begin
set beg=0
set end=n-1
set mid=(beg+end)/2
while((beg<=end) and(a[mid]!=item) do
if(a[mid]<item) then
set beg=mid+1
else
set end=mid-1
endif
set mid=(beg+end)/2
endwhile
if(beg>end) then
set loc=-1
else
set loc=mid
endif
Binary Search C++ Program
 #include<iostream>
 using namespace std;
 int main()
 {
 int i, arr[10], num, first, last, middle;
 cout<<"Enter 10 Elements (in ascending order): ";
 for(i=0; i<10; i++)
 cin>>arr[i];
 cout<<"\nEnter Element to be Search: ";
 cin>>num;
 first = 0;
 last = 9;
 middle = (first+last)/2;
 while(first <= last)
 {
 if(arr[middle]<num)
 first = middle+1;
 else if(arr[middle]==num)
 {
 cout<<"\nThe number, "<<num<<" found at Position "<<middle;
 break;
 }
 else
 last = middle-1;
 middle = (first+last)/2;
 }
 if(first>last)
 cout<<"\nThe number, "<<num<<" is not found in given Array";
 cout<<endl;
 return 0;
 }
Introduction to Sorting
Definition:
Sorting arranges data in a sequence which
makes searching easier.
The Sorting organizes a collection of data into
either ascending or descending order
according to specified criteria.
A={3162134590}

A={0112334569}
Types of Sorting Techniques
There are many types of Sorting techniques,
differentiated by their efficiency and space
requirements. Following are some sorting
techniques which we will be covering in next
sections.
1. Bubble Sort
2. Insertion Sort
3. Selection Sort
4. Quick Sort
5. Merge Sort
6. Heap Sort
Bubble Sort
Bubble sort is a simple way to sort a list of numbers.
1.Start at the Beginning: Begin with the first two
elements of the list.
2.Compare and Swap: If the first element is greater
than the second, swap them.
3.Continue Along the List: Move to the next pair of
adjacent elements and repeat the comparison and
swap if necessary.
4.Repeat the Process: Once you reach the end of the
list, start over from the beginning and repeat the
steps.
5.Stop When No Swaps Occur: The sorting is
complete when you go through the list without
making any swaps
Bubble Sort Algorithm
Begin
for i=0 to (n-1) by 1 do
for j=0 to (n-i-1) by 1 do
if(a[j]>a[j+1]) then
set temp=a[j]
set a[j]=a[j+1]
set a[j+1]=temp
endif
endfor
endfor
end
Sorting using Bubble Sort Algorithm
 #include<iostream>
 using namespace std;
 int main()
 {
 int n, i, arr[10], j, temp;
 cout<<"Enter the Size (max. 10): ";
 cin>>n;
 cout<<"Enter "<<n<<" Numbers: ";
 for(i=0; i<n; i++)
 cin>>arr[i];
 cout<<"\nSorting the Array using Bubble Sort Technique..\n";
 for(i=0; i<(n-1); i++)
 {
 for(j=0; j<(n-i-1); j++)
 {
 if(arr[j]>arr[j+1])
 {
 temp = arr[j];
 arr[j] = arr[j+1];
 arr[j+1] = temp;
 }
 }
 }
 cout<<"\nArray Sorted Successfully!\n";
 cout<<"\nThe New Array is: \n";
 for(i=0; i<n; i++)
 cout<<arr[i]<<" ";
 cout<<endl;
 return 0;

SELECTION SORT
The selection sort algorithm sorts an array by
repeatedly finding the minimum element from unsorted
part and putting it at the beginning.
Idea:
Find the smallest element in the array
Exchange(or swap) it with the element in the first position
Find the second smallest element and exchange it with the
element in the second position
Continue until the array is sorted
Disadvantage:
Running time depends only slightly on the amount of
order in the file
SELECTION SORT
Selection Sort Algorithm
Begin
for i=0 to n-1 by 1 do
set smallest = i
for j=i+1 to n by 1 do
If a[smallest]<a[j] then
smallest=j;
endif
endfor
set temp=a[smalest]
set a[smalest]=a[i]
set a[i]=temp
endfor
end
C++ function for Selection Sort
 #include<iostream>
 using namespace std;
 int main()
 {
 int tot, arr[50], i, j, temp, small, chk, index;
 cout<<"Enter the Size of Array: ";
 cin>>tot;
 cout<<"Enter "<<tot<<" Array Elements: ";
 for(i=0; i<tot; i++)
 cin>>arr[i];
 for(i=0; i<(tot-1); i++)
 {
 chk=0;
 small = arr[i];
 for(j=(i+1); j<tot; j++)
 {
 if(small>arr[j])
 {
 small = arr[j];
 chk++;
 index = j;
 }
 }
 if(chk!=0)
 {
 temp = arr[i];
 arr[i] = small;
 arr[index] = temp;
 }
 }
 cout<<"\nSorted Array is:\n";
 for(i=0; i<tot; i++)
 cout<<arr[i]<<" ";
 cout<<endl;
 return 0;
INSERTION SORT
Insertion sort is a method for sorting a list by building
a sorted section one element at a time.
1.Start with the First Element: Begin with the first
element, which is already considered sorted.
2.Take the Next Element: Go to the next element in
the list.
3.Find Its Place: Compare this element with the ones in
the sorted section and find the correct position for it.
4.Insert It: Move the elements as needed and insert the
new element in its correct place.
5.Repeat: Continue this process for each element in the
list until all elements are sorted.
 #include<iostream>
 using namespace std;
 int main()
 {
 int arr[50], tot, i, j, k, elem, index;
 cout<<"Enter the Size for Array: ";
 cin>>tot;
 cout<<"Enter "<<tot<<" Array Elements: ";
 for(i=0; i<tot; i++)
 cin>>arr[i];
 for(i=1; i<tot; i++)
 {
 elem = arr[i];
 if(elem<arr[i-1])
 {
 for(j=0; j<=i; j++)
 {
 if(elem<arr[j])
 {
 index = j;
 for(k=i; k>j; k--)
 arr[k] = arr[k-1];
 break;
 }
 }
 }
 else
 continue;
 arr[index] = elem;
 }
 cout<<"\nThe New Array (Sorted Array):\n";
 for(i=0; i<tot; i++)
 cout<<arr[i]<<" ";
 cout<<endl;
 return 0;
 }
INSERTION SORT
The Insertion Sort traverse the array and insert
each element into the sorted part of the list
where it belongs. It involves pushing down the
larger elements in the sorted part
INSERTION SORT ALGORITHM
APPLICATION ACTIVITY
Q1. APPLY ALGORITHM TO SOLVE COMPLEX
MATHEMATICAL FUNCTIONS
A. QUADRATIC EQUATION
Below you are given the algorithm and pseudo
code to resolve quadratic equation: ax2+ b x+
c=0; where a, b and c are not equal to zero.
Improve the algorithm and pseudo code to
resolve quadratic equation since some of steps
to resolve a quadratic equation are not given.
Draw the flow chart of the algorithm to solve
quadratic equation.
#include<iostream>
#include<math.h>
using namespace std;
void eq(int,int,int);
int main(){
int a,b,c;
cout<<"Enter the coefficient A : \n ";
cin>>a,
cout<<"Enter the coefficient B : \n ";
cin>>b;
cout<<"Enter the coefficient C : \n ";
cin>>c;
eq(a,b,c);
return 0;
}
void eq(int a, int b, int c){
float d,root1,root2;
d=pow(b,2)-4*a*c;
if(d<0){
cout<<"\n RESULT : \n Roots are
complex/imaginary number.\n";
}
else if(d==0){
cout<<"\n RESULT : \n Both roots are real numbers
and equal.\n";
root1 = -b /(2* a);
cout<<" Root of quadratic equation is:\n Root-1 = Root-2
= "<<root1<<endl;
}
else{
cout<<"\n RESULT : \n Roots are real numbers and
unequal.\n";
root1 = ( -b + sqrt(d)) / (2* a);
root2 = ( -b - sqrt(d)) / (2* a);
cout<<" Roots of quadratic equation are:\n Root-1 =
"<<root1<<"\n Root-2 = "<<root2<<endl;
}
}
FACTORIAL, FIBONACCI SERIES AND
PALINDROME FUNCTIONS
Definition:
A recursive function is a function that calls
itself during its execution.
The Recursive function repeats itself several
times, outputting the result at the end of each
iteration.
In this section we are going to discuss the
following recursive functions:
FACTORIAL FUNCTION
#include<iostream>
using namespace std;
int fact(int);
int main(){
int a,b;
cout<<"Enter an Integer number to find an integer:\n";
cin>>a;
b=fact(a);
cout<<"\n The Factorial number of : "<<a<<"!
="<<b<<endl;
return 0;
}
int fact(int n){
if(n<=1)
return 1;
else
return n*fact(n-1);
}
FIBONACCI SERIES

In mathematics, the Fibonacci numbers are integer numbers in the following


sequence: 0, 1, 1, 2,
3, 5, 8..., this series of integers is called the Fibonacci sequence. Fibonacci
sequence is characterized by the fact that every number after the first two is the
sum of the two preceding one. It means that except for the first two terms of the
sequence every other term is the sum of the previous two terms.
The pseudo code of Fibonacci function
Fibo(n)
Begin
if n <= 1 then
Return n;
else
Return Call Fibo(n-1) + Call
Fibo(n-2);
endif
End
Euclid's GCD (greatest common denominator)
The greatest common denominator, or GCD,
between two numbers is the greatest integer that
divides both given numbers.
Cpp function to calculate GCD

int gcd(int a, int b)


{
// Everything divides 0
if (a == 0)
return b;
if (b == 0)
return a;

// base case
if (a == b)
return a;

// a is greater
if (a > b)
return gcd(a-b, b);
else
return gcd(a, b-a);
}
Prime Number
C++ Program to check Prime Number
bool isPrime(int n)
{
if (n <= 1)
return false;

// Check from 2 to n-1


for (int i = 2; i < n; i++)
if (n % i == 0)
return false;

return true;
}
Palindrome function
 The algorithm which would get out any amount palindrome
numbers on screen.
 Let take: 300003 310013 320023 330033 340043
350053.
 Findings: written algorithm how to check if it is a
palindrome number or not.
 Here is algorithm for how i check if its palindrome or not:

You might also like