0% found this document useful (0 votes)
7 views67 pages

DS Module1

The document provides an overview of data structures, focusing on their classification into linear and non-linear types, along with specific examples such as arrays, stacks, queues, linked lists, trees, and graphs. It details the characteristics, advantages, and disadvantages of arrays, including their declaration, initialization, and basic operations like insertion and deletion. Additionally, it includes algorithms for inserting and deleting elements in arrays, emphasizing the importance of data structures in efficient data management.

Uploaded by

muhsin7aliyar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views67 pages

DS Module1

The document provides an overview of data structures, focusing on their classification into linear and non-linear types, along with specific examples such as arrays, stacks, queues, linked lists, trees, and graphs. It details the characteristics, advantages, and disadvantages of arrays, including their declaration, initialization, and basic operations like insertion and deletion. Additionally, it includes algorithms for inserting and deleting elements in arrays, emphasizing the importance of data structures in efficient data management.

Uploaded by

muhsin7aliyar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

MODULE 1:

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.

Classification of Data Structure:

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:

- Array Data Structure


In an array, elements in memory are arranged in continuous memory. All the elements of an array are of
the same type. And, the type of elements that can be stored in the form of arrays is determined by the
programming language.

- Stack Data Structure


In stack data structure, elements are stored in the LIFO principle. That is, the last element stored in a
stack will be removed first.It works just like a pile of plates where the last plate kept on the pile will be
removed first.

- Queue Data Structure


Unlike stack, the queue data structure works in the FIFO principle where first element stored in the
queue will be removed first.

2
It works just like a queue of people in the ticket counter where first person on the queue will get the
ticket first.

- Linked List Data Structure


In linked list data structure, data elements are connected through a series of nodes. And, each node
contains the data items and address to the next node.

- Graph Data Structure


In graph data structure, each node is called vertex and each vertex is connected to other vertices
through edges.

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.

Need Of Data structure :

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.

ARRAY DATA STRUCTURE

- 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).

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:

int baz [5] = { };

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:

int foo [5]= {16, 2, 77, 40, 12071};

The number of values between braces {] shall not be greater than the number of elements in the array.
Eg 2:

int bar [5] = { 10, 20, 30 };

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 {}:

int foo [] = { 16, 2, 77, 40, 12071 };

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:

int foo[5]; // declaration of a new array


foo[2] = 75; // access to an element of array.

Some other valid operations with arrays:

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 foo [] = {16, 2, 77, 40, 12071};


int i, result=0;

int main ()
{

7
for ( i=0 ; i<5 ; i++ )
{
result += foo[i];
}
cout << result;
return 0;
}

Output : 12206

Representation of array in memory

- 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.

- Index starts with 0.


- Array length is 9 which means it can store 9 elements.
- Each element can be accessed via its index. For example, we can fetch an element at index 6 as
23.

MULTIDIMENSIONAL ARRAYS

- Multidimensional arrays can be described as "arrays of arrays".


- For example, a bi-dimensional array can be imagined as a two-dimensional table made of
elements, all of them hold same type of elements.

8
Table represents a bi-dimensional array of 3 per 5 elements of type int. The C++ syntax for this is

int Table [3][5];

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.

char century [100][365][24][60][60];

Basic Operations in the Arrays


The basic operations in the Arrays are insertion, deletion, searching, display, traverse, and update. These
operations are usually performed to either modify the data in the array or to report the status of the
array.

Following are the basic operations supported by an array.

Traverse − print all the array elements one by one.


Insertion − Adds an element at the given index.
Deletion − Deletes an element at the given index.
Search − Searches an element using the given index or by the value.
Update − Updates an element at the given index.
Display − Displays the contents of the array.

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

Insertion of a new element in an array can be done in three ways:


- insertion at the beginning of the array
- Insertion at the end of the array
- Insertion at required position

ALGORITHM

1. [Initialize the value of i] Set i= len


2. Repeat for i= len down to pos
[Shift the elements down by 1 position]
Set a[i+ 1] = a[i]
[End of loop]
3. [Insert the element at required position]
Set a[pos]= num
4. [Reset len] Set len =len +1
5. Display the new list of arrays 6.
End

Insertion in Linear Array-an element at the beginning of the array


- In this case we have to move all the elements one position backwards to make a hole at the
beginning of array.
- Though the insertion process is not difficult but freeing the first location for new element
involves movement of all the existing elements. This is the worst case scenario in insertion in a
linear array.
- In the below example, array elements from index 1 to index 8 have to moved one position
backwards so that the new element 44 can be stored at index 1

Initially

After movement of elements backwards

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

For All Elements in A


Move to next adjacent location

A[FIRST] = New_Element

end

Insertion in Linear Array- at the end of the array

- 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

SEEK Location index

For All Elements from A[index + 1] to A[N]


Move to next adjacent location

A[index + 1] = New_Element

end

Insertion in Linear Array- at the give position J

- 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 movement of elements

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

SEEK Location index

For All Elements from A[index] to A[N]


Move to next adjacent location

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

Deletion in Array- an element at the beginning of the array


- In this case we have to move all the elements one position forward to fill the position of the
element at the beginningof array.
- Though the deletion process is not difficult but moving all elements one position forward
involve movement of all the existing elements except the one being deleted. This is the worst
case scenario in deletion in a linear array.
- In the example array elements from index 1 to index 8 have to moved one position forwards so
that the first element is replaced by second, second by third and so on

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

Deletion in Array – an element at the give position J


- Let J be any location in the array for one existing element. We have to delete the element at J
position.
- To do this starting from J every element is moved one place forward so that the element after
index J comes to position of Jth element.
- This is the average case scenario in deletion in linear array.
- In the example array ,elements from index J (4) to index 8 have to moved one position forward
so that an element at index 4 is replaced by element at index 5. Similarly element at 6th postion
comes at 5th position, element at 7th position comes at 6th position and element at 8th
position replaces element at 7th position completing the deletion process

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()
{

int arr[50], size, i, del, count=0;

cout<<"Enter array size : ";


cin>>size;
cout<<"\nEnter array elements :: \n";

for(i=0; i<size; i++)


{
cout<<"\nEnter arr["<<i<<"] Element :: ";
cin>>arr[i];
}

16
cout<<"\nEnter element to be delete :: ";
cin>>del;

for(i=0; i<size; i++)


{
if(arr[i]==del)
{
for(int j=i; j<(size-1); j++)
{
arr[j]=arr[j+1];
}
count++;
break;
}
}
if(count==0)
{
cout<<"\nElement not found..!!\n";
}
else
{
cout<<"\nElement deleted successfully..!!\n";
cout<<"\nNow the new array is ::\n";
for(i=0; i<(size-1); i++)
{
cout<<arr[i]<<" ";
}
}
cout<<"\n";

return 0;
}

Output

Enter array size: 8


Enter array elements ::
Enter arr[0] Element :: 1
Enter arr[1] Element :: 2
Enter arr[2] Element :: 3
Enter arr[3] Element :: 4

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

- Traversal in a Linear Array is the process of visiting each element once.


- Traversal is done by starting with the first element of the array and reaching to the last.
- Traversal operation can be used in counting the array elements, printing the values stored in an
array, updating the existing values or summing up all the element values.
- If a user wants to do similar calculation on each element of the array she will use traversal
operation.

Algorithm for Traversing an Array:

Consider the array of the following linear array with LB=0 and UB=9

Step 01: Start


Step 02: [Initialize counter variable. ] Set i = LB.
Step 03: Repeat for i = LB to UB.
Step 04: Apply process to arr[i].
Step 05: [End of loop. ]
Step 06: Stop

Program to traverse an array

#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 is the process of finding a given value position in a list of values.


- It decides whether a search key is present in the data or not.
- It is the algorithmic process of finding a particular item in a collection of items.
- It can be done on internal data structure or on external data structure.

Searching Techniques

To search an element in a given array, it can be done in following ways:

1. Sequential Search
2. Binary Search

1. Sequential Search/ Linear search

Sequential search is also called as Linear Search.


Sequential search starts at the beginning of the list and checks every element of the list.
It is a basic and simple search algorithm.
Sequential search compares the element with all the other elements given in the list. If the element is
matched, it returns the value index, else it returns -1.

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 -

First, we have to traverse the array elements using a for loop.


- In each iteration of for loop, compare the search element with the current array element, and -
- If the element matches, then return the index of the corresponding array element.
- If the element does not match, then move to the next element.
- If there is no match or the search element is not present in the given array, return -1.

Let the element to be searched is K = 41

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

Time Complexity of Linear search

Case Time Complexity


Best Case O(1)
Average Case O(n)
Worst Case O(n)

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).

Linear search 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;
}

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).

Conditions for when to apply Binary Search in a Data Structure:

To apply Binary Search algorithm:


- The data structure must be sorted.
- Access to any element of the data structure takes constant time.

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 -

Let the element to search is, K = 56

We have to use the below formula to calculate the mid of the array -

mid = (beg + end)/2

So, in the given array -

beg = 0
end = 8

mid = (0 + 8)/2 = 4. So, 4 is the mid of the array.

23
Now, the element to search is found. So algorithm will return the index of the element matched.

Algorithm:

Binary_Search(a, lower_bound, upper_bound, val)

// '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

Step 1: set beg = lower_bound,


end = upper_bound,
pos = - 1
Step 2: repeat steps 3 and 4 while beg <=end
Step 3: set mid = (beg + end)/2
Step 4: if a[mid] = val
set pos = mid
print pos
go to step 6

else if a[mid] > val


set end = mid - 1

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

Binarysearch (a,n, item)


Step 1 Pos = -1
Step 2 beg=1
end= n
Step 3 While beg <=end
set mid = (beg + end)/2
Step 4 If item == a[mid] then
Pos = mid
End of loop
Step 5 Else if item > a[mid]
beg = mid + 1
Step 6 Else
end = mid -1

Binary search program:

#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];
}

// initialize the starting and ending variable's values


st = 0;
end = num - 1; // size of array (num) - 1

// define the item or value to be search


cout << " Define a value to be searched from sorted array: " << endl;
cin >> tgt;

// 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:

Different sorting techniques are:


- Selection sort
- Insertion sort
- Quick sort
- Bubble sort
- Merge sort

Selection sort

- Selection sort is a simple sorting algorithm.


- This sorting algorithm is an in-place comparison-based algorithm in which the list is divided into
two parts, the sorted part at the left end and the unsorted part at the right end. Initially, the
sorted part is empty and the unsorted part is the entire list.
- The smallest element is selected from the unsorted array and swapped with the leftmost element,
and that element becomes a part of the sorted array. This process continues moving unsorted
array boundary by one element to the right.

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.

Consider the following depicted array as an example.

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

Step 1 − Set MIN to location 0


Step 2 − Search the minimum element in the list
Step 3 − Swap with value at location MIN
Step 4 − Increment MIN to point to next element
Step 5 − Repeat until list is sorted

Pseudocode

procedure selection sort


list : array of items
n : size of list

29
for i = 1 to n - 1
/* set current element as minimum*/
min = i

/* check the element to be minimum */

for j = i+1 to n
if list[j] < list[min] then
min = j;
end if
end for

/* swap the minimum element with the current element*/


if indexMin != i then
swap list[min] and list[i]
end if
end for

end procedure

Advantages of Selection Sort Algorithm

● Simple and easy to understand.


● Works well with small datasets.

Disadvantages of the Selection Sort Algorithm


● Selection sort has a time complexity of O(n^2) in the worst and average case.
● Does not work well on large datasets.
● Does not preserve the relative order of items with equal keys which means it is not stable.

Selection sort complexity

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

Case Time Complexity


Best Case
O(n2)

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.

We take an unsorted array for our example.

Insertion sort compares the first two elements.

It finds that both 14 and 33 are already in ascending order. For now, 14 is in sorted sub-list.

Insertion sort moves ahead and compares 33 with 27.

And finds that 33 is not in the correct position.

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.

These values are not in a sorted order.

33
So we swap them.

However, swapping makes 27 and 10 unsorted.

Hence, we swap them too.

Again we find 14 and 10 in an unsorted order.

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.

Step2 - Pick the next element, and store it separately in a key.

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.

Step 6 - Repeat until the array is sorted.

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;

// Function to print an array


void printArray(int array[], int size) {
for (int i = 0; i < size; i++) {
cout << array[i] << " ";
}
cout << endl;
}

void insertionSort(int array[], int size) {


for (int step = 1; step < size; step++) {
int key = array[step];
int j = step - 1;

// 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:

Time Complexity of Insertion Sort

The worst-case time complexity of the Insertion sort is O(N^2)

The average case time complexity of the Insertion sort is O(N^2)

The time complexity of the best case is O(N).

Space Complexity of Insertion Sort

The auxiliary space complexity of Insertion Sort is O(1)

Characteristics of Insertion Sort


- This algorithm is one of the simplest algorithms with a simple implementation
- Basically, Insertion sort is efficient for small data values
- Insertion sort is adaptive in nature, i.e. it is appropriate for data sets that are already partially
sorted.

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:

There are many different choices for picking pivots.

- Always pick the first element as a pivot.


- Always pick the last element as a pivot (implemented below)
- Pick a random element as a pivot.
- Pick the middle as the pivot.

Algorithm:

QUICKSORT (array A, start, end)


{
1 if (start < end)
2{
3 p = partition(A, start, end)
4 QUICKSORT (A, start, p - 1)
5 QUICKSORT (A, p + 1, end)
6
}
}

Partition Algorithm:
The partition algorithm rearranges the sub-arrays in a place.

PARTITION (array A, start, end)


{
1 pivot ? A[end]
2 i ? start-1

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.

Let the elements of array are -

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.

Now, a[left] = 24, a[right] = 19, and a[pivot] = 24.


Because, a[pivot] > a[right], so, algorithm will swap a[pivot] with a[right], and pivot moves to right, as -

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

Case Time Complexity


Best Case O(n*logn)
Average Case O(n*logn)
Worst Case O(n2)

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

Space Complexity. - O(n*logn)


Stable - NO
The space complexity of quicksort is O(n*logn).

Program

#include <iostream>

using namespace std;

/* function that consider last element as pivot,


place the pivot at its exact position, and place
smaller elements to left of pivot and greater
elements to right of pivot. */
int partition (int a[], int start, int end)
{
int pivot = a[end]; // pivot element

42
int i = (start - 1);

for (int j = start; j <= end - 1; j++)


{
// If current element is smaller than the pivot
if (a[j] < pivot)
{
i++; // increment index of smaller element
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
int t = a[i+1];
a[i+1] = a[end];
a[end] = t;
return (i + 1);
}

/* function to implement quick sort */


void quick(int a[], int start, int end) /* a[] = array to be sorted, start = Starting index, end = Ending index
*/
{
if (start < end)
{
int p = partition(a, start, end); //p is the partitioning index
quick(a, start, p - 1);
quick(a, p + 1, end);
}
}

/* function to print an array */


void printArr(int a[], int n)
{
int i;
for (i = 0; i < n; i++)
cout<<a[i]<< " ";
}
int main()
{
int a[] = { 23, 8, 28, 13, 18, 26 };
int n = sizeof(a) / sizeof(a[0]);

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

1. SPARSE MATRIX REPRESENTATION


2. POLYNOMIAL REPRESENTATION

SPARSE MATRIX REPRESENTATION

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.

Representation of sparse matrix

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

Array representation of the sparse matrix

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 -

Consider the sparse matrix -

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.

what's the benefit of using the sparse matrix?


Consider the case if the matrix is 8*8 and there are only 8 non-zero elements in the matrix,
then the space occupied by the sparse matrix would be 8*8 = 64, whereas the space occupied by the
table represented using triplets would be 8*3 = 24.

Program:Implementation of array representation of 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

1. Addition of Sparse Matrices:

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

In the above table,

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

POLYNOMIAL REPRESENTATION USING ARRAYS OF STRUCTURE:

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.

Points to keep in Mind while working with Polynomials:


- The sign of each coefficient and exponent is stored within the coefficient and the exponent itself
- Additional terms having equal exponent is possible one
- The storage allocation for each term in the polynomial must be done in ascending and
descending order of their exponent

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

Polynomial Structure Declaration

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;
}

//Read Second poly


cout << "\n\nSecond Polynomial\n"; end = NULL; 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 (poly2 == NULL)
poly2 = 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.

While adding two polynomials, following cases need to be considered.

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.

2. When the degrees of corresponding terms of the polynomials are different:

Here, the term with the larger degree pre-dominates.

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.

Flowchart of first 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

[Initialize segment variables]


[Initialize Counter] Set i=0,j=0,k=0

Repeat while i<t1 and j<t2


IF p1[i].expo=p2[j].expo, THEN
p3[i].coeff=p1[i].coeff+p2[i].coeff
p3[k].expo=p1[i].expo
[Increase counter] Set i=i+1,j=j+1,k=k+1
ELSE IF p1[i].expo > p2[j].expo, THEN
p3[k].coeff=p1[i].coeff
p3[k].expo=p1[i].expo
[Increase counter] Set i=i+1,k=k+1
ELSE
p3[k].coeff=p2[j].coeff
p3[k].expo=p2[j].expo
Set j=j+1,k=k+1
[End of If]
[End of loop]

Repeat while i<t1


p3[k].coeff=p1[i].coeff
p3[k].expo=p1[i].expo
Set i=i+1,k=k+1
[End of loop]

Repeat while j<t2


p3[k].coeff=p2[j].coeff
p3[k].expo=p2[j].expo
Set j=j+1,k=k+1
[End of loop]
Return k
EXIT

Program

Polynomial addition using array


Program to add two polynomials and display resultant polynomial

#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

Enter the no of terms in 1st polynomial:3

Enter the coefficient & exponents:5


5

Enter the coefficient & exponents:7


3

Enter the coefficient & exponents:6


2

Enter the no of terms in 2nd polynomial:2

Enter the coefficient & exponents:6


5

Enter the coefficient & exponents:3


2

1st polynomial is:


5 x^ 5 + 7 x^ 3 +6 x^ 2

2nd polynomial is:


6 x^ 5 + 3 x^ 2

Resultant polynomial is:11 x^ 5 + 7 x^ 3 + 9 x^ 2

67

You might also like