DS Module1
DS Module1
Data Structure
A data structure is a storage that is used to store and organize data. It is a way of arranging data on a
computer so that it can be accessed and updated efficiently.
- A data structure is not only used for organizing the data. It is also used for processing, retrieving,
and storing data.
- There are different basic and advanced types of data structures that are used in almost every
program or software system that has been developed.
Linear data structure: Data structure in which data elements are arranged sequentially or linearly,
where each element is attached to its previous and next adjacent elements, is called a linear data
structure.
Example: array, stack, queue, linked list, etc.
- Static data structure: Static data structure has a fixed memory size. It is easier to access the
elements in a static data structure.
Eg: array
- Dynamic data structure: In dynamic data structure, the size is not fixed. It can be randomly
updated during the runtime which may be considered efficient concerning the memory (space)
complexity of the code.
Eg: queue, stack, etc.
Non-linear data structure: Data structures where data elements are not placed sequentially or linearly
are called non-linear data structures. In a non-linear data structure, we can’t traverse all the elements in
a single run only.
Eg:trees and graphs.
1
Types of data structures:
2
It works just like a queue of people in the ticket counter where first person on the queue will get the
ticket first.
3
- Trees Data Structure
Similar to a graph, a tree is also a collection of vertices and edges. However, in tree data structure, there
can only be one edge between two vertices.
The structure of the data and the synthesis of the algorithm are relative to each other. Data
presentation must be easy to understand so the developer, as well as the user, can make an efficient
implementation of the operation.
Data structures provide an easy way of organizing, retrieving, managing, and storing data.
- Data structure modification is easy.
- It requires less time.
- Save storage memory space.
- Data representation is easy.
- Easy access to the large database.
4
- In C++, array index starts from 0. We can store only fixed set of elements in C++ array.
- Elements of an array can be accessed arbitrarily using its indices. They can be used to store a
collection of any type of primitive data type, including int, float, double, char, etc.
- An array in C/C++ can also store derived data types like structures, pointers, and other data
types, which is an addition.
Array Index:
The location of an element in an array has an index, which identifies the element. Array index starts
from 0.
Array element:
Items stored in an array is called an element. The elements can be accessed via its index.
Array Length:
The length of an array is defined based on the number of elements an array can store. In the above
example, array length is 6 which means that it can store 6 elements.
Advantages of arrays:
- Code Optimization (less code)
- Random Access
- Easy to traverse data
- Easy to manipulate data
- Easy to sort data etc.
Disadvantages of arrays:
- Fixed size
Array Types
There are 2 types of arrays in C++ programming:
- Single Dimensional Array
- Multidimensional Array
Array Declaration
A typical declaration for an array in C++ is:
5
type name [elements];
where
- type is a valid type (such as int, float ...),
- name is a valid identifier
- the elements field (which is always enclosed in square brackets [1), specifies the size of the
array.
Eg: Thus, the x array, with five elements of type int, can be declared as:
int x [5];
NOTE:
- The elements field within square brackets [], representing the number of elements in the array,
must be a constant expression, since arrays are blocks of static memory whose size must be
known at compile time.
INITIALIZING ARRAYS
- By default, are left uninitialized. This means that none of its elements are set to any particular
value; their contents are undetermined at the point the array is declared.
The initializer can even have no values, just the braces:
This creates an array of five int values, each initialized with a value of zero:
But, the elements in an array can be explicitly initialized to specific values when it is declared, by
enclosing those initial values in braces {}. For example:
The number of values between braces {] shall not be greater than the number of elements in the array.
Eg 2:
6
If declared with less, the remaining elements are set to their default values (which for fundamental
types, means they are filled with zeroes).
When an initialization of values is provided for an array, C++ allows the possibility of leaving the square
brackets empty[]. In this case, the compiler will assume automatically a size for the array that matches
the number of values included between the braces {}:
ARRAY ACCESSING
The values of any of the elements in an array can be accessed just like the value of a regular variable of
the same type. The syntax is:
name[index]
Eg:
foo[0] = a;
foo[i] = 75;
b = foo [i+2];
foo[foo[i]] = foo[i] + 5;
EXAMPLE:
// arrays example
#include <iostream>
using namespace std;
int main ()
{
7
for ( i=0 ; i<5 ; i++ )
{
result += foo[i];
}
cout << result;
return 0;
}
Output : 12206
- Arrays are represented as a collection of buckets where each bucket stores one element.
- These buckets are indexed from ‘0’ to ‘n-1’, where n is the size of that particular array.
- For example, an array with size 10 will have buckets indexed from 0 to 9.
- This indexing will be similar for the multidimensional arrays as well. If it is a 2-dimensional array,
it will have sub-buckets in each bucket.
- Then it will be indexed as array_name[m][n], where m and n are the sizes of each level in the
array.
MULTIDIMENSIONAL ARRAYS
8
Table represents a bi-dimensional array of 3 per 5 elements of type int. The C++ syntax for this is
Eg:the way to reference the second element vertically and fourth horizontally in an expression would
be:
Table[1][3]
Multidimensional arrays are not limited to two indices (i.e., two dimensions). They can contain as many
indices as needed.
Array operations:
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.
9
- This is done using input statements of the programming languages
ALGORITHM
Initially
10
After insertion
Algorithm
We assume A is an array with N elements. The maximum numbers of elements it can store is defined by
MAX. We shall first check if an array has any empty space to store any element and then we proceed
with the insertion process.
begin
IF N = MAX, return
ELSE
N=N+1
A[FIRST] = New_Element
end
- In this case we don’t have to move any elements since the action here will be just to append the
element at the location after the last element. This is the best case scenario.
- In the example array no elements are moved. The new element is stored in index 9
Initially
After insertion
Algorithm
11
We assume A is an array with N elements. The maximum numbers of elements it can store is defined by
MAX.
begin
IF N = MAX, return
ELSE
N=N+1
A[index + 1] = New_Element
end
- Let J be any location in the array ofone element already existing. We have to add the new
element at J position.
- To do this, starting from J, every element is moved one place backwards so that a hole is created
at J and new element can be inserted here. This is the average case scenario.
- In the example array ,elements from index J (4) to index 8 have to moved one position
backwards so that a new element can be stored at index J(4)
Initially
After insertion
12
Algorithm
We assume A is an array with N elements. The maximum numbers of elements it can store is defined by
MAX.
begin
IF N = MAX, return
ELSE
N=N+1
A[index] = New_Element
end
———————————
Program of the insert of an element in an array at a specific position in C++
#include <iostream>
using namespace std;
int main()
{
int array[100], position, c, n, value;
cout<<"Enter number of elements in array\n"<<endl;
cin>>n;
cout<<"Enter elements\n"<<endl;
for (c = 0; c < n; c++)
{
cin>>array[c];
}
cout<<"Enter the location where you wish to insert an element\n"<<endl;
cin>>position;
cout<<"Enter the value to insert\n"<<endl;
cin>>value;
for (c = n - 1; c >= position - 1; c--)
{
array[c+1] = array[c];
}
array[position-1] = value;
13
cout<<"Resultant array is\n"<<endl;
for (c = 0; c <= n; c++)
{
cout<<array[c];
}
return 0;
}
Output:
Deletion operation
Deletion in array means removing an element and replacing it with the next element or element present
at next index. It involves three cases
- deletion at the beginning of the array
- Deletion at the end of the array
- Deletion at specific position
14
Deletion in Array – an element at the end of the array
- In this case we don’t have to move any elements since the action here will be just removing the
last element.
- This is done by redefining the index of last element of linear array = N-1. This is the best case
scenario in deletion in a linear array.
- In the example array no elements are moved. The last element is removed by setting the index
of last element as 7
15
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.
1. Start
2. Set J = K
3. Repeat steps 4 and 5 while J < N
4. Set LA[J] = LA[J + 1]
5. Set J = J+1
6. Set N = N-1
7. Stop
———————————————
Write a program to delete an element from the array
#include<iostream>
using namespace std;
int main()
{
16
cout<<"\nEnter element to be delete :: ";
cin>>del;
return 0;
}
Output
17
Enter arr[4] Element :: 5
Enter arr[5] Element :: 6
Enter arr[6] Element :: 7
Enter arr[7] Element :: 8
Enter element to be delete :: 5
Element deleted successfully..!!
Now the new array is ::
1234678
Process returned 0
——————————————
Traversal
Consider the array of the following linear array with LB=0 and UB=9
#include <iostream>
using namespace std;
int main()
{
18
int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array
//traversing array
for (int i = 0; i < 5; i++)
{
cout<<arr[i]<<"\n";
}
}
Output:
10
0
20
0
30
——————————
Search operation
Searching Techniques
1. Sequential Search
2. Binary Search
19
The above figure shows how sequential search works. It searches an element or value from an array till
the desired element or value is not found. If we search the element 25, it will go step by step in a
sequence order. It searches in a sequence order. Sequential search is applied on the unsorted or
unordered list when there are fewer elements in a list.
The steps used in the implementation of Linear Search are listed as follows -
Now, start from the first element and compare K with each element of the array.
The value of K, i.e., 41, is not matched with the first element of the array. So, move to the next element.
And follow the same process until the respective element is found.
Now, the element to be searched is found. So algorithm will return the index of the element matched.
20
Algorithm:
Linear_Search(a, n, val) // 'a' is the given array, 'n' is the size of given array, 'val' is the value to search
Step 1: set pos = -1
Step 2: set i = 1
Step 3: repeat step 4 while i <= n
Step 4: if a[i] == val
set pos = i
print pos
go to step 6
[end of if]
set ii = i + 1
[end of loop]
Step 5: if pos = -1
print "value is not present in the array "
[end of if]
Step 6: exit
OR
Let
'a' - is the given array,
'n' - is the size of given array,
Item - is the value to search
Linear_Search(a, n, item)
Step 1: set pos = -1
Step 2: set i = 1
Step 3: repeat while ( i <= n ) AND (a[i] !=item )
i = i+1
If (a[i] ==item )
pos = i
Else
Return pos
21
Best Case Complexity - In Linear search, best case occurs when the element we are finding is at the first
position of the array. The best-case time complexity of linear search is O(1).
Average Case Complexity - The average case time complexity of linear search is O(n).
Worst Case Complexity - In Linear search, the worst case occurs when the element we are looking is
present at the end of the array. The worst-case in linear search could be when the target element is not
present in the given array, and we have to traverse the entire array. The worst-case time complexity of
linear search is O(n).
#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;
}
22
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 item is found at middle element, the process is terminated.
- If the iitem is not found at middle element, choose which half will be used as the next search
space.
- If the item is smaller than the middle element, then the left side is used for next search.
- If the item is larger than the middle element, then the right side is used for next search.
- This process is continued until the item is found or the total search space is exhausted.
Example:
Let the elements of array are -
We have to use the below formula to calculate the mid of the array -
beg = 0
end = 8
23
Now, the element to search is found. So algorithm will return the index of the element matched.
Algorithm:
// 'a' is the given array, 'lower_bound' is the index of the first array element, 'upper_bound' is the index
of the last array element, 'val' is the value to search
else
set beg = mid + 1
24
[end of if]
[end of loop]
Step 5: if pos = -1
print "value is not present in the array"
[end of if]
Step 6: exit
OR
#include <iostream>
#include <conio.h>
using namespace std;
int main ()
{
// declaration of the variables and array
int arr[100], st, mid, end, i, num, tgt;
cout << " Define the size of the array: " << endl;
cin >> num; // get size
// enter only sorted array
cout << " Enter the values in sorted array either ascending or descending order: " << endl;
// use for loop to iterate values
25
for (i = 0; i < num; i++)
{
cout << " arr [" << i << "] = ";
cin >> arr[i];
}
// use while loop to check 'st', should be less than equal to 'end'.
while ( st <= end)
{
// get middle value by splitting into half
mid = ( st + end ) / 2;
/* if we get the target value at mid index, print the position and exit from the program. */
if (arr[mid] == tgt)
{
cout << " Element is found at index " << (mid + 1);
exit (0); // use for exit program the program
}
// check the value of target element is greater than the mid element' value
else if ( tgt > arr[mid])
{
st = mid + 1; // set the new value for st variable
}
// check the value of target element is less than the mid element' value
else if ( tgt < arr[mid])
{
end = mid - 1; // set the new value for end variable
}
}
cout << " Number is not found. " << endl;
return 0;
}
SORTING
26
Sorting in C++ is a concept in which the elements of an array are rearranged in a logical order. This order
can be from lowest to highest or highest to lowest. Sorting an unsorted array helps to solve many
problems such as searching for the minimum or maximum element, etc.Arranging things in a sorted
manner makes it easier to analyze and search for a particular element among the collection of elements.
Sorting algorithm:
A Sorting Algorithm is used to rearrange 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.
Sorting techniques:
Selection sort
27
- This algorithm is not suitable for large data sets as its average and worst case complexities are of
Ο(n2), where n is the number of items.
For the first position in the sorted list, the whole list is scanned sequentially. The first position where 14
is stored presently, we search the whole list and find that 10 is the lowest value.
So we replace 14 with 10. After one iteration 10, which happens to be the minimum value in the list,
appears in the first position of the sorted list.
For the second position, where 33 is residing, we start scanning the rest of the list in a linear manner.
We find that 14 is the second lowest value in the list and it should appear at the second place. We swap
these values.
After two iterations, two least values are positioned at the beginning in a sorted manner.
The same process is applied to the rest of the items in the array.
Following is a pictorial depiction of the entire sorting process −
28
Algorithm
Pseudocode
29
for i = 1 to n - 1
/* set current element as minimum*/
min = i
for j = i+1 to n
if list[j] < list[min] then
min = j;
end if
end for
end procedure
Now, let's see the time complexity of selection sort in best case, average case, and in worst case. We will
also see the space complexity of the selection sort.
1. Time Complexity
Average Case
O(n2)
Worst Case
O(n2)
30
Best Case Complexity - It occurs when there is no sorting required, i.e. the array is already sorted. The
best-case time complexity of selection sort is O(n2).
Average Case Complexity - It occurs when the array elements are in jumbled order that is not properly
ascending and not properly descending. The average case time complexity of selection sort is O(n2).
Worst Case Complexity - It occurs when the array elements are required to be sorted in reverse order.
That means suppose you have to sort the array elements in ascending order, but its elements are in
descending order. The worst-case time complexity of selection sort is O(n2).
Space Complexity
Space Complexity
O(1)
Stable
YES
The space complexity of selection sort is O(1). It is because, in selection sort, an extra variable is
required for swapping.
Program:
#include<iostream>
using namespace std;
void swapping(int &a, int &b) { //swap the content of a and b
int temp;
temp = a;
a = b;
b = temp;
}
void display(int *array, int size) {
for(int i = 0; i<size; i++)
cout << array[i] << " ";
cout << endl;
}
void selectionSort(int *array, int size) {
31
int i, j, imin;
for(i = 0; i<size-1; i++) {
imin = i; //get index of minimum data
for(j = i+1; j<size; j++)
if(array[j] < array[imin])
imin = j;
//placing in correct position
swap(array[i], array[imin]);
}
}
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n]; //create an array with given number of elements
cout << "Enter elements:" << endl;
for(int i = 0; i<n; i++) {
cin >> arr[i];
}
cout << "Array before Sorting: ";
display(arr, n);
selectionSort(arr, n);
cout << "Array after Sorting: ";
display(arr, n);
}
32
INSERTION SORT
Insertion sort is a simple sorting algorithm that works similar 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.
It finds that both 14 and 33 are already in ascending order. For now, 14 is in sorted sub-list.
It swaps 33 with 27. It also checks with all the elements of sorted sub-list. Here we see that the sorted
sub-list has only one element 14, and 27 is greater than 14. Hence, the sorted sub-list remains sorted after
swapping.
By now we have 14 and 27 in the sorted sub-list. Next, it compares 33 with 10.
33
So we swap them.
We swap them again. By the end of third iteration, we have a sorted sub-list of 4 items.
This process goes on until all the unsorted values are covered in a sorted sub-list. Now we shall see some
programming aspects of insertion sort.
34
Algorithm
The simple steps of achieving the insertion sort are listed as follows -
Step 1 - If the element is the first element, assume that it is already sorted. Return 1.
Step3 - Now, compare the key with all elements in the sorted array.
Step 4 - If the element in the sorted array is smaller than the current element, then move to the next
element. Else, shift greater elements in the array towards the right.
35
Step 5 - Insert the value.
OR
Now we have a bigger picture of how this sorting technique works, so we can derive simple steps by which
we can achieve insertion sort.
Step 1 − If it is the first element, it is already sorted. return 1;
Step 2 − Pick next element
Step 3 − Compare with all elements in the sorted sub-list
Step 4 − Shift all the elements in the sorted sub-list that is greater than the
value to be sorted
Step 5 − Insert the value
Step 6 − Repeat until list is sorted
PROGRAM
// Insertion sort in C++
#include <iostream>
using namespace std;
// Compare key with each element on the left of it until an element smaller than
// it is found.
// For descending order, change key<array[j] to key>array[j].
while (key < array[j] && j >= 0) {
array[j + 1] = array[j];
--j;
}
36
array[j + 1] = key;
}
}
// Driver code
int main() {
int data[] = {9, 5, 1, 4, 3};
int size = sizeof(data) / sizeof(data[0]);
insertionSort(data, size);
cout << "Sorted array in ascending order:\n";
printArray(data, size);
}
Complexity Analysis of Insertion Sort:
QUICK SORT
QuickSort is a sorting algorithm based on the Divide and Conquer algorithm that picks an element as a
pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in
the sorted array.
The key process in quickSort is a partition(). The target of partitions is to place the pivot (any element
can be chosen to be a pivot) at its correct position in the sorted array and put all smaller elements to the
left of the pivot, and all greater elements to the right of the pivot.
37
Partition is done recursively on each side of the pivot after the pivot is placed in its correct position and
this finally sorts the array.
Choice of Pivot:
Algorithm:
Partition Algorithm:
The partition algorithm rearranges the sub-arrays in a place.
38
3 for j ? start to end -1 {
4 do if (A[j] < pivot) {
5 then i ? i + 1
6 swap A[i] with A[j]
7 }}
8 swap A[i+1] with A[end]
9 return i+1
}
Working
Now, let's see the working of the Quicksort Algorithm.
To understand the working of quick sort, let's take an unsorted array. It will make the concept more
clear and understandable.
In the given array, we consider the leftmost element as pivot. So, in this case, a[left] = 24, a[right] = 27
and a[pivot] = 24.
Since, pivot is at left, so algorithm starts from right and move towards left.
Now, a[pivot] < a[right], so algorithm moves forward one position towards left, i.e.
39
Now, a[left] = 19, a[right] = 24, and a[pivot] = 24. Since, pivot is at right, so algorithm starts from left and
moves to right.
As a[pivot] > a[left], so algorithm moves one position to right as -
Now, a[left] = 9, a[right] = 24, and a[pivot] = 24. As a[pivot] > a[left], so algorithm moves one position to
right as -
Now, a[left] = 29, a[right] = 24, and a[pivot] = 24. As a[pivot] < a[left], so, swap a[pivot] and a[left], now
pivot is at left, i.e.
Since, pivot is at left, so algorithm starts from right, and move to left. Now, a[left] = 24, a[right] = 29, and
a[pivot] = 24. As a[pivot] < a[right], so algorithm moves one position to left, as -
40
Now, a[pivot] = 24, a[left] = 24, and a[right] = 14. As a[pivot] > a[right], so, swap a[pivot] and a[right],
now pivot is at right, i.e. -
Now, a[pivot] = 24, a[left] = 14, and a[right] = 24. Pivot is at right, so the algorithm starts from left and
move to right.
Now, a[pivot] = 24, a[left] = 24, and a[right] = 24. So, pivot, left and right are pointing the same element.
It represents the termination of procedure.
Element 24, which is the pivot element is placed at its exact position.
Elements that are right side of element 24 are greater than it, and the elements that are left side of
element 24 are smaller than it.
Now, in a similar manner, quick sort algorithm is separately applied to the left and right sub-arrays. After
sorting gets done, the array will be -
41
Quicksort complexity
Now, let's see the time complexity of quicksort in best case, average case, and in worst case. We will
also see the space complexity of quicksort.
1. Time Complexity
Best Case Complexity - In Quicksort, the best-case occurs when the pivot element is the middle element
or near to the middle element. The best-case time complexity of quicksort is O(n*logn).
Average Case Complexity - It occurs when the array elements are in jumbled order that is not properly
ascending and not properly descending. The average case time complexity of quicksort is O(n*logn).
Worst Case Complexity - In quick sort, worst case occurs when the pivot element is either greatest or
smallest element. Suppose, if the pivot element is always the last element of the array, the worst case
would occur when the given array is sorted already in ascending or descending order. The worst-case
time complexity of quicksort is O(n2).
2. Space Complexity
Program
#include <iostream>
42
int i = (start - 1);
43
cout<<"Before sorting array elements are - \n";
printArr(a, n);
quick(a, 0, n - 1);
cout<<"\nAfter sorting array elements are - \n";
printArr(a, n);
return 0;
}
Output:
APPLICATION OF ARRAYS
MATRIX
A matrix can be defined as a two-dimensional array having 'm' rows and 'n' columns. A matrix with m
rows and n columns is called m × n matrix. It is a set of numbers that are arranged in the horizontal or
vertical lines of entries.
SPARSE MATRIX
Sparse matrices are those matrices that have the majority of their elements equal to zero. In other
words, the sparse matrix can be defined as the matrix that has a greater number of zero elements than
the non-zero elements.
Why is a sparse matrix required if we can use the simple matrix to store elements?
There are the following benefits of using the sparse matrix -
Storage - We know that a sparse matrix contains lesser non-zero elements than zero, so less memory
can be used to store elements. It evaluates only the non-zero elements.
44
Computing time: In the case of searching in sparse matrix, we need to traverse only the non-zero
elements rather than traversing all the sparse matrix elements. It saves computing time by logically
designing a data structure traversing non-zero elements.
The non-zero elements in the sparse matrix can be stored using triplets that are rows, columns, and
values. There are two ways to represent the sparse matrix that are listed as follows -
- Array representation
- Linked list representation
Representing a sparse matrix by a 2D array leads to the wastage of lots of memory. This is because
zeroes in the matrix are of no use, so storing zeroes with non-zero elements is wastage of memory. To
avoid such wastage, we can store only non-zero elements. If we store only non-zero elements, it reduces
the traversal time and the storage space.
In 2D array representation of sparse matrix, there are three fields used that are named as -
Row - It is the index of a row where a non-zero element is located in the matrix.
Column - It is the index of the column where a non-zero element is located in the matrix.
Value - It is the value of the non-zero element that is located at the index (row, column).
Example:
Let's understand the array representation of sparse matrix with the help of the example given below -
In the above figure, we can observe a 5x4 sparse matrix containing 7 non-zero elements and 13 zero
elements. The above matrix occupies 5x4 = 20 memory space. Increasing the size of matrix will increase
the wastage space.
45
The tabular representation of the above matrix is given below -
- In the above structure, first column represents the rows, the second column represents the
columns, and the third column represents the non-zero value.
- The first row of the table represents the triplets
- The first triplet represents that the value 4 is stored at 0th row and 1st column. Similarly, the
second triplet represents that the value 5 is stored at the 0th row and 3rd column. In a similar
manner, all triplets represent the stored location of the non-zero elements in the matrix.
- The size of the table depends upon the total number of non-zero elements in the given sparse
matrix.
- Above table occupies 8x3 = 24 memory space which is more than the space occupied by the
sparse matrix.
#include <stdio.h>
int main()
{
// Sparse matrix having size 4*5
int sparse_matrix[4][5] =
{
{0 , 0 , 6 , 0 , 9 },
{0 , 0 , 4 , 6 , 0 },
{0 , 0 , 0 , 0 , 0 },
{0 , 1 , 2 , 0 , 0 }
};
// size of matrix
int size = 0;
46
for(int i=0; i<4; i++)
{
for(int j=0; j<5; j++)
{
if(sparse_matrix[i][j]!=0)
{
size++;
}
}
}
// Defining final matrix
int matrix[3][size];
int k=0;
// Computing final matrix
for(int i=0; i<4; i++)
{
for(int j=0; j<5; j++)
{
if(sparse_matrix[i][j]!=0)
{
matrix[0][k] = i;
matrix[1][k] = j;
matrix[2][k] = sparse_matrix[i][j];
k++;
}
}
}
// Displaying the final matrix
for(int i=0 ;i<3; i++)
{
for(int j=0; j<size; j++)
{
printf("%d ", matrix[i][j]);
printf("\t");
}
printf("\n");
}
return 0;
}
Output:
47
SPARSE MATRIX OPERATIONS
Let us look at the addition of sparse matrices in coordinate list representation. Below we have 2 sparse
matrices,
We want to add these matrices and store a new matrix in ‘C’. In mathematical form, it will be done as,
Here we added every element of matrix ‘A’ to the corresponding element of matrix ‘B’ and store the
result in matrix ‘C’. Now let us do the same thing using coordinate list representation. In the matrix ‘A’,
let us create a horizontal table to store the data of this matrix.
48
the first column of the table as seen above, store the information about the matrix i.e., rows, columns,
and non-zero elements. Now we will fill the non-zero elements with the row and column number as
49
0th column represents, no. of rows, no. of columns, and total no. of non-zero elements.
1st column represents, 1st row and 5th column of the sparse matrix contain ‘3’ element.
2nd column represents, the 2nd row and 3rd column of the sparse matrix containing the ‘9’ element.
3rd column represents, the 2nd row and the 5th column of the sparse matrix contains the ‘4’ element.
And so on.
In this way, we have filled non-zero elements in the table. We will create this table in C++ by using
structures. We will see this later. Now let us create a table of matrix ‘B’ also, after that we will see the
procedure of addition.
50
The size of 3rd structure will be = no. of non-zero elements in (Matrix A + Matrix B) = 6 + 6 = 12.
If none of them is matching and none of them is added then at most 12 elements are required. Here we
will not take space for 12 elements as we know the answer. There are only 9 non-zero elements. So, we
will take space for 9 elements.
We have created another structure to store the result of the addition. Here 5 and 6 are rows and
columns of the matrix. It will store the result of the addition of the above 2 matrices. And we leave the
0th column last field as empty in the table as we don’t know the number of non-zero elements. We will
fill this field as we got the result of the addition. We know that the 0th row or ‘i’ contains row number
and the 1st row or ‘j’ contains column number of non-zero elements of the matrix.
51
52
So first check the 1st column of both the table. A [0] [1] = 1 and B [0] [1] = 1, rows number are matching.
A [1] [1] = 5 and Array B [1] [1] = 1, here B’s column < A’s column, so insert B’s data into ‘C’ and
increment ‘j’.
Now, check the ith column of ‘A’ with the jth column of ‘B’. A [0] [2] = 2 and B [0] [2] = 2, both have
same row number so check for column. A [1] [2] = 3 and B [1] [2] = 3, both have the same column
number, so here both rows and column numbers are matching so add the element and insert this data
in ‘C’ and increment both ‘i’ as well as ‘j’.
53
In this way, we will perform addition. If both arrays have the same row number and column number
then add those elements and insert them in ‘C’. If the row number of one table is less than the row
number of another table, then insert that row that has a smaller number and increment counter of that
table. If the column number of one table is less than the column number of another table, then insert
that column that has a smaller number and increment counter of that table. So
54
55
This is the final table we got after the addition. Here we have also filled that we have 9 non-zero
elements. So, this is how addition is performed in sparse matrices.
POLYNOMIAL REPRESENTATION
A polynomial p(x) is the expression in variable x which is in the form (axn + bxn-1 + …. + jx+ k), where a,
b, c …., k fall in the category of real numbers and 'n' is non negative integer, which is called the degree of
polynomial.
An essential characteristic of the polynomial is that each term in the polynomial expression consists of
two parts:
- one is the coefficient
- other is the exponent
Example:
10x2 + 26x, here 10 and 26 are coefficients and 2, 1 is its exponential value.
Representation of polynomials
Polynomial can be represented in the various ways. These are:
- By the use of arrays
56
- By the use of Linked List
There may arise some situation where you need to evaluate many polynomial expressions and perform
basic arithmetic operations like addition and subtraction with those numbers. For this, you will have to
get a way to represent those polynomials. The simple way is to represent a polynomial with degree 'n'
and store the coefficient of n+1 terms of the polynomial in the array. So every array element will consist
of two values:
- Coefficient and
- Exponent
struct polynomial
{
int coefficient;
int exponent;
};
struct polynomial A
Program:
Representation of polynomial using cpp
#include <iostream>
#include <iomanip.h>
using namespace std;
struct poly {
int coeff;
int pow_val;
poly* next;
};
class add {
poly *poly1, *poly2, *poly3;
public:
add() { poly1 = poly2 = poly3 = NULL; }
void addpoly();
void display();
57
};
void add::addpoly()
{
int i, p;
poly *newl = NULL, *end = NULL;
cout << "Enter highest power for x\n"; cin >> p;
//Read first poly
cout << "\nFirst Polynomial\n"; for (i = p; i >= 0; i--) {
newl = new poly;
newl->pow_val = p;
cout << "Enter Co-efficient for degree" << i << ":: "; cin >> newl->coeff;
newl->next = NULL;
if (poly1 == NULL)
poly1 = newl;
else
end->next = newl;
end = newl;
}
//Addition Logic
poly *p1 = poly1, *p2 = poly2;
end = NULL;
while (p1 != NULL && p2 != NULL) {
if (p1->pow_val == p2->pow_val) {
newl = new poly;
newl->pow_val = p--;
newl->coeff = p1->coeff + p2->coeff;
newl->next = NULL;
if (poly3 == NULL)
58
poly3 = newl;
else
end->next = newl;
end = newl;
}
p1 = p1->next;
p2 = p2->next;
}
}
void add::display()
{
poly* t = poly3;
cout << "\n\nAnswer after addition is : ";
while (t != NULL) {
cout.setf(ios::showpos);
cout << t->coeff;
cout.unsetf(ios::showpos);
cout << "X" << t->pow_val;
t = t->next;
}
}
int main()
{
add obj;
obj.addpoly();
obj.display();
}
Output:
POLYNOMIAL ADDITION
To add two polynomials using structure, just add the coefficient parts of the polynomials having same
exponent.
59
Add Polynomial Function Declaration
addPolynomial(
struct polynomial p1[10],
struct polynomial p2[10],
int t1,
int t2,
struct polynomial p3[10]);
Example:
Consider a polynomial 3x2+2x+7;
here, the total number of terms is 3.
The coefficients of each term are 3, 2, 7
and degrees 2, 1, 0 respectively.
When the degrees of corresponding terms of the two polynomials are same:
This is the normal case when corresponding coefficients of each term can be added directly. For
example, the sum of the polynomials
60
5x3+2x2+7
7x3+9x2+12
-------------------
12x3+11x2+19 is a simple addition where all the degrees of the corresponding terms are same.
9x4+5x3+ +2x
3x4+ +4x2+7x
------------------------
12x4+5x3+4x2+9x
Algorithm explanation
Let ‘m’ and ‘n’ be the no. of terms of the two polynomials represented by arrays a[] and b[]. Sum of
them is represented by c[] and i, j, k respectively are the subscripts used to denote the various elements
of arrays a, b and c. The logic of the program is written in 3 parts considering each possibility in order to
obtain the exact sum.
First part
Variables i, j, k are set to zero in the beginning. The condition that ‘m’ and ‘n’ should be greater than
zero is what is required for execution of the first part. Then, the next checking condition that a[i] equal
to b[j] determines whether the degree of the first term of the first polynomial is equal to the degree of
the first term of the second polynomial. If this is true, then the sum of the coefficients a[i+1] and b[j+1]
is stored in c[k+1] and the degree a[i] or b[i] (both same) in c[k]. As, summation takes place with one
term from each of the polynomials, each term gets reduced by 1. Also, the subscripts ‘i’ and ‘j’ are
moved forward by 2 as each term has a degree and a coefficient.
If the checking condition becomes false, then next check a[i] greater than b[j] finds out whether the
degree of the first polynomial is greater than that of the second. If this is true, then the degree of the
sum c[k] is set to a[i] and the coefficient c[k+1] to a[i+1]. The no. of terms of first polynomial gets
reduced by 1 and the subscript ‘i’ also moved forward by 2.If this condition becomes false, then the
61
degree of the sum c[k] becomes b[j] and c[k+1]=b[j+1]. The no. of terms of second polynomial gets
reduced by 1 and the subscript ‘j’ is moved forward by 2.
After executing just one of these possible cases, control finally reaches the statement k=k+2 that moves
forward the subscript of array ‘c’ by 2. When either ‘m’ or ‘n’ becomes zero, control exits the loop and
moves to the second part.
Second part
As there can be some terms remaining in either first polynomial or second after the execution of first
part, they need to be added to the polynomial sum. This is done by iterating a set of statements for the
condition that the no. of terms is greater than zero taking each independently.
The no. of terms of 1st polynomial is checked first. If it is greater than zero, then the coefficient of
polynomial sum where it is standing at present is equated to the current coefficient of the 1st
polynomial. Similarly degree also has to be equated correspondingly. Then, no. of terms of 1st
polynomial gets reduced by 1 and subscripts ‘i’ and ‘k’ skip forward by 2. The loop is executed as long as
the condition is true.
62
Third part
The second part is repeated here for second polynomial. After all the remaining terms of it gets added to
the sum, the control exits the loop and final result is obtained.
63
Polynomial Addition Algorithm
Program
#include<iostream>
64
using namespace std;
struct poly
{
int coeff;
int exp;
};
class polynomial
{
struct poly p[20];
public:
int n;
void read();
void display();
polynomial operator +(polynomial);
};
void polynomial::read()
{
int i;
for(i=0;i<n;i++)
{
cout<<”\n Enter the coefficient & exponents:”;
cin>>p[i].coeff>>p[i].exp;
}
}
void polynomial::display()
{
for(int i=0;i<n;i++)
{
cout<<p[i].coeff<<” x^ ”<<p[i].exp;
if(i!=n-1)
cout<<” + ”;
}
cout<<”\n”;
}
polynomial polynomial::operator +(polynomial p2)
{
polynomial p3;
int i=0,j=0,k=0;
while((i<n)&&(j<p2.n))
{
if(p[i].exp>p2.p[j].exp)
{
65
p3.p[k]=p[i];
i++;
}
else if(p[i].exp<p2.p[j].exp)
{
p3.p[k]=p2.p[j];
j++;
}
else
p3.p[k].coeff=p[i].coeff+p2.p[j].coeff;
p3.p[k].exp=p[i].exp;
i++;
j++;
}
k++;
}
while(i<n)
{
p3.p[k]=p[i];
i++;
k++;
}
while(j<p2.n)
{
p3.p[k]=p2.p[j];
j++;
k++;
}
p3.n=k;
return p3;
}
int main()
{
polynomial p1,p2,p3;
cout<<”\n Enter the no of terms in 1st polynomial:”;
cin>>p1.n;
p1.read();
cout<<”\n Enter the no of terms in 2nd polynomial:”;
cin>>p2.n;
p2.read();
cout<<”\n 1st polynomial is:\n”;
p1.display();
66
cout<<”\n 2nd polynomial is:\n”;
p2.display();
p3=p1+p2;
cout<<”\n Resultant polynomial is:”;
p3.display();
}
OUTPUT
67