Senior Five Mce MPC Notes Data Structure and Algorithms
Senior Five Mce MPC Notes Data Structure and Algorithms
Senior Five Mce MPC Notes Data Structure and Algorithms
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
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)
branches
leaves
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:
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
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
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
// 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;
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: