0 ratings0% found this document useful (0 votes) 380 views17 pagesMCS-021 2022 23 Solved Assignment
IGNOU BCA 3rd Semester MCS-021 Solved Assignment
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
- Binary Tree Construction
- Multiple Stacks in a Queue
- Search Algorithms
- AVL Trees
eb Tousy Stvny HeLtee
[Link] fF Suaie Poona
Course Code : MCS-021
Course Title : Data and File Structures
Assignment Number : MCA(II)/021/Assignment/2022-23,
ae ‘er
Welghtage : 25% [Link] =
Last Dates for Submission : 3ist October, 2022 (for July, 2022 wey
15th April, 2023 (for January, 2023 session)
1. Write an algorithm that converts a Tree into a Binary Tree.
Ans.
include
dinelude
using namespace std;
1/ Data structure to store a Binary Tree node
struct Node
{
int data;
Node *left, right;
Nodetint data)
{
this->data = data;
thise-left ~ thise-right — aullpte;
struct Trunk:
{
Trunk *prev;
string str
Trunk(Trunk *prev, string ste)
{
this >prev= prev;
thisstr = str
i
// Helper function to print branches of the binary tree
void showTrunks(Trunk *p)
{ sw
it(o==ouipt)
return; :
Sone
showTrunks(o->prev);
Ignou Study Helper-Sunil Poonia Page 1geste Tonon Stvey Here
[Link] Nasi’ Sua. Poowia
cout << p->str;
[/ Recursive function to print binary tree
// ituses inorder traversal
void printTree(Node *root, Trunk *prev, bool isLeft)
{
if (root
ullptr)
string prev_st
Trunk *trun|
ew Trunk(prev, prev_ste);
printTree(root-left, trunk, true);
if (prev)
trunk->str ="
else if (isteft)
trunk->ste =
prevstr=" |"
showTrunks(trunk);
cout << root >data << endl;
if (prev)
prev->str = prev_str;
trunkostr=" |
printTree(root->right, trunk, false);
int maing)
{
Node* root = nuliptr;
Ji Construct above tree
root = new Node(1);
Ignou Study Helper-Sunil Poonia Page 2geste Tonon Stvey Here
‘[Link] \ooit Suae Poona
root->left = new Node(2);
root->right = new Node(3);
root-left-left = new Node(4);
root-aleft->right = new Node(5);
root-right->left = new Node(6);
root-right->right = new Node(7);
root->left->left->left = new Node(8};
root-sleft-left->right
rootlettright>le
root-loft-wright-oright = new Noda(4),
root->right->leftleft= new Node12);
root->right->left-right = new Node(13);
root->right->right->eft = new Node(14);
root-sright-sright-sright = new Node(15);
// print constructed binary tree
printTree(root, nullptr, false);
mas
me
“11
“12
“3.
oe
15
2. Is it possible to implement multiple stacks in a Queue. Justify your answer,
Ans.
We are given a stack data structure with push and pop operations, the task isto implement’@ queue using instances of stack data
structure and operations on them.
Ignou Study Helper-Sunil Poonia Page‘[Link] Nasi’ Suae Poona
Pat
Stack
Insertion and Deletion
Nappen on same end
fp Pe
Queue
Insertion and Deletion —
ferent ends
rrgueie Devteve
First in first out
A queue canbe implemented using two stacks. Let queue to be implemented be q and stacks used to implement q be stack and
stack2. q can be implemented in tivo ways:
‘Method 4 (By making en Queue operation costly) This method makes sure that oldest entered element Is always atthe top of
stack 1, so that de Queue operation just pops from stack. To put the element at top of stackl, stack? is used,
enQueuela, x):
‘+ While stack1 is not empty, push everything from stackl to stack2
‘+ Push x'to stack! (assuming size of stacks is unlimited).
‘© Push everything back to stack.
Here time complexity will be O(n)
deQueue(a):
‘+ If stack1 is empty then error
‘+ Pop an item from stack and retuitn it
Here time complexity will be O(1)
// C++ program to implement Queue using
[/ wo stacks with costly enQueue()
include
vsing namespace se ig
struct Queue {
stackcint> $1, 52;
void enQueuetint x)
{
// Move all elements from s1 to 52
while ([Link]() {
[Link]([Link]());
Ignou Study Helper-Sunil Poonia Page +es Teun Stony Heztee
‘[Link] NEY Suwit Poona
[Link]|)s
)
Af Push item into s1
[Link](x);
// Push everything back to st
while ([Link]()] {
[Link]([Link]()};
s2-popl)
t
// Dequeue an item from the queue
int deQueue()
{
A] if first stack is empty
if (sLempty()) {
cout <<"Qis Empty",
exit();
}
UP Return top of sh
intx= sLtopl);
[Link]();
return x;
k
1 Driver code
int maing)
{
Queue a:
[Link]( 1);
[Link](2);
[Link]( 3);
cout << qdequeue() <<"\
cout << [Link]() <"y
cout << [Link]() <<"
t
von
1
Ignou Study Helper-Sunil Poonia PageS25 touon Sr ese
‘[Link] NEY Suwit Poona
2
3
‘Complexity Analysis:
+ Time Complexity:
‘+ Push operation: O()
In the worst case we have empty whole of stack
+ Pop operation: O(1).
Same 8s pop operation in stack
Auxillary Space: O(N).
Use of stack for storing values.
into stack 2
Method 2 (By making deQueue operation costy)in this method, in en-queue operation, the new elements entered at the top of
stack. In de-queue operation if stack2 is empty then all the elements are moved to stack? and finally top of stack? is returned.
enqueue(a, *)
1) Push x to stacki (assuming size of stacks is unlimited)
Here time complexity will be O(1)
dequeue(q)
1) If both stacks are empty then error.
2) If stack? is empty
While stack1 is not empty, push everything from stack1 to stack2.
3) Pop the elemerit frum stavk2 and reuutn
Here time complexity will be O(n)
Method 2 is definitely better than method 1.
Method 1 moves all the elements twice in enQueue operation, while method 2 (in deQueue operation) moves the elements once
and moves elements only if stack2 empty, So, the amortized complexity of the dequeue operation becomes (-) (1)
Implementation of method 2:
/* Program to implement a queue using two stacks *)
Winchude vor
finde st o> fey
:
{* structure of a stack node:
struct sNode {
int data;
struct sNode* next;
k
{* Function to push an item to stack*/
void pushistruct sNode** top_ref, int new_data);
/* Function to pop an item from stack*/
int poplstruct sNode** top_ref);
Ignou Study Helper-Sunil Poonia Page 6es Teun Stony Heztee
‘[Link] NEY Suwit Poona
* structure of queue having two stacks */
struct queue {
struct sNode* stack;
struct sNode* stack2;
i
/* Function to engueue an item to queve */
void endueve(struct queuet g, int x)
nl
push[&q->stacki,»);
{* Function to deQueue an item from queue */
int deQueue(struct queue* g)
{
ints
/* Wf both stacks are empty then error */
if (q->stack1 == NULL && q->stack: NULL)
print("[Link] empty");
getchar();
‘exit{O),
/* Move elements from stacki to stack 2 only if
stack2 is empty */
if (q->stack2 == NULL] {
while (q>stackl = NULL) [
x= pop(&q->stackl);
push(&q->stack2, x):
1
) fg et
x= popltq->stact2}s Ne)
return ¥;
{* Function to push an item to stack*/
void push(struct sNode** top_ref, int new data)
{
/* allocate node */
struct sNode* new_node = (struct sNode*)malloc|sizeot{struct sNode)};
if (new_node == NULL} {
printf("stack overflow \n");
Ignou Study Helper-Sunil Poonia Page?25 touon Sr ese
‘[Link] NEY Suwit Poona
getchar();
-exit(0);
7? putinthe data */
new_node->dat:
7/* link the old list off the new node */
new_node->next = (*top_refl;
/* move the head to point to the new node */
(*top_ref) = new node;
/* Function to pop an item from stack*/
int pop(struct sNode** top_ref)
{
int res;
strict sNode* top;
ik stacks empty then error */
if (top_ref == NULL) (
printf("Stack underflow \n";
getchar();
exitiO};
else {
top = *top_ref;
res= top >data;
*top_ref= top >next;
free(top):
{/* Univer function to test anove functions */
int maing
{
/* Create a queue with items 12 3*/
struct queue” q= (struct queue*)malloe(sizeof{struct queue)};
g->stackl = NULL;
q->stack2 = NULL;
engueve(q, 1)
encuevela, 2);
enQuevela, 3);
Ignou Study Helper-Sunil Poonia Page 8ges Too Srv Meee
‘[Link] NEY Suwit Poona
/* Dequeue items */
printf("%d", deQueue(q));
printi("%d", dequeue(a);
printf("éd", deueue()}
return 0;
}
Output:
Complexity Analysis:
+ Time Complexity:
+ Push operation: O(1),
Same a8 pop operation in stack.
‘+ Pop operation: O(N).
In the worst case we have empty whole of stack 1 into stack 2,
‘+ Auxiliary Space: O(N).
Use of stack for storing values.
3. List the names of all SEARCH Algorithms along with their Complenities (Best case, Average case and Worst case). List as
‘many names as possible along with their year of Invention and Inventor. Make necessary assumptions.
‘Ans. Searching algorithm: Searching algorithm is the process of fetching a specific element in a collection of elements. The
collection can be an array or a linked list. if you find the element in the list, the process is considered successful, and it returns the
location of that element.
And in contrast, if you do not find the element, it deems the search unsuccessful
‘Two prominent search strategies are extensively used to find a specific item ona list, However, the algorithm chosen is
determined by the lis's organization.
1. Linear Search
2. Binary Search
4. Linear search: Linear search, often known as sequential search, is the most basic search technique. In this type of search, you go
through the entire list and try to fetch a match for a single element. If you find ammatth, then the address of the matching target
element is returned
On the other hand, if the element is not found, then it returns a NULL value.
Algorithm of the Linear Search
Linear Search ( Array Arr, Value a} // Arris the name of the array, and a isthe searched element.
Step 1: Set 0 0 // I's the Index of an array which starts from 0
Step 2: i> n then goto step 7 // nis the number of elements in array
Step 3: if Arr[i] =a then go to step 6
Step 4: Set] tole 1
Ignou Study Helper-Sunil Poonia Page9ges Too Srv Meee
‘[Link] NEY Suwit Poona
step 5: Goto step 2
step 6: Print element 2 found at index i and go to step 8
step 7: Print element not found
step 8: Exit
‘The Complexity of Linear Search Algorithm
You have three different complexities faced while performing Linear Search Aig
1m, they are mentioned as follows.
1. Best Case
2. Worst Case
3. Average Case
‘You will learn about each’one of them in a bit more detail,
Best Case Complexity
‘+The element being searched could be found in the first position,
‘+ Inthis case, the search ends with a single successful comparison,
‘+ Thus, in the best-case scenario, the linear search algorithm performs O(2) operations.
Worst Case Complexity
‘+The element being searched may be at the last position in the array or not at all.
‘+ Inthe first case, the search succeeds in ‘n’ comparisons.
Inthe next case, the search fails after ‘n’ comparisons)
‘+ Thus, in the worst-case scenario, the'linear search algorithm performs O(n) operations.
Average Case Complexity
‘When the element to be searched is in the middle of the array, the average case of the Linear Search Algorithm is O(n).
Next, you will learn about the Space Complexity of Linear Search Algorithm.
Example:
1, C++ code to linearly search x in arti. fx
J's present then return its location, otherwise
{return 2
include
using namespace std;
int search(int arr{}, int N, int x)
a
inci
for (i= 0; 1< Nj i++)
if (arr{i] == x)
return
return 4 um,
} i
fet
1 briver's code Noes
Ignou Study Helper-Sunil Poonia Page 10ge fs Touou Stuy HeLree
ie
‘[Link] \ooit Suae Poona
int main(void)
{
int ar{] = (2,3, 4,10, 40);
int x= 10;
int N = szeof(art) / sizeot(art{0))
1 Function call
Int result = search(arr, Nx);
(result==-1)
2 cout ce "Element is nat presentin array"
+ cout << "Element is present at index" << result;
tun 6
, ~
ont =)
dementispresentatindexs “Seaoe”
2. Binary search: Binary search Is the search technique that works efficiently on sorted lists, Hence, to search an element into
some list using the binary search technique, we must ensure that the listissorted.
Binary search follows the divide and conquer approach in which the list is divided into two halves, and the item is compared with
the middle element of the list. f the match is found then, the location of the middle element is returned, Otherwise, we search
into either of the halves depending upon the result produced through thé match.
Algorithm of Binary Search
Binary_Search(e, lower_bound, upper_bouridWal) //'a! isthe elven atray, Jower_bound! isthe index of the first array element
pper_bound’ isthe index of the last array element, Vallis ti valUéto search
Step 1: set beg = lower_bound, end = upper bound, pos =-1
Step 2: repeat steps 3 and 4 while beg val
set end = mid-1
else
set beg = mid +1
[end of if]
[end af loop]
Step 5: if pos =-1
print "value isnot present in the array"
lend of if
step 6: exit
Ignou Study Helper-Sunil Poonia Page 11ges Too Srv Meee
‘[Link] NEY Suwit Poona
The Complexity of Binary Search Algorithm
Best Case Complexity: in Binary search, best case occurs when the element to search is found in first comparison, ie., when the
first middle element itself is the element to be searched, The best-case time complexity of Binary search is O(1).
‘Average Case Complexity: The average case time complexity of Binary search is Ollogn).
Worst Case Complexity: In Binary search, the worst case occurs, when we have to keep reducing the search space til thas only
one element. The worst case time complexty of shar search s Og)
va fe
include
using namespace std; se nh
int binarySearch(int all, int beg, int end, int val)
{
int mid;
iflend >= bee)
(
mid = (beg +end)/2:
/* ifthe item to be searched is present at middle */
if{almid] == val)
{
retuirn mid+1;
1
J” if the item to be searched is smaller than middle, then it can only be in left subarray */
clse iffalmid] < val)
t
return binarySearch(a, mid#1, end, val)
}
/* ifthe item to be searched is greater than middle, then it can only be in right subarray */
else
{
return binarySearchja, beg, mic-t, val);
+
)
return -1
}
int main() {
int a] = {10, 12, 24, 29, 39, 40, 51, 56, 70); // given array
int val = 51; // value to be searched
int n= sizeofia) / sizeof(al0)); // size of array
int res = binarySearch(2, 0, n-, val); // Store result
cout<<"The elements of the array are";
for(int
coutecaicc* f
coutec"\nelement to be searched is-"
using namespace std
class Node
{ public:
int data, height;
Node * left_child;
Node * right_child;
Ignou Study Helper-Sunil Poonia Page 1325 touon Sr ese
‘[Link] NEY Suwit Poona
class avi{,
publi:
vosetroseenu — AE
EY
if(root == NULL)
return -1;
return (root->height);
int get_balance_factor(Node * root){
if(root
NULL)
return 0;
return (get_height(root->left_child) - get_height(root->right child);
// Clockwise Rotation
Node * LL_rotation(Node * root){
Node *
= root left_child:
root-left_child = child-sright_child;
child->right_child = rants
root >helght = max(get_height(root-pleft-child), get_height{root->right_child)) +2;
child->height = max(get_height{child->left_child), get_height(child->right_child))+ 1;
return child;
// Anti-Clockwise Rotation
Ignou Study Helper-Sunil Poonia Page 1+[Link] Nasi’ Sua. Poowia
Node * RR_rotation(Node * root}{
geste Tonon Stvey Here
miotikaiinaneicay CAS
child->left_child = root; Noe
root->height = max|get_height(root->left_child), get_height(root->right_child)) + 2;
child->height = max(get_height(child->left child), get_height(child->right_child)) + 1;
return child
// Pre-order traversal of the tree
void pre_order(Node * root)
£ iffroot
Ly)
{ coutdata <<"
pre_order(root->left_child);
pre_order(roat->right_child);
4/ BNL insertion
Node * insert(Node * root, int new_data)
{
JL ST Insertion |
iffoot == NULL
root = new Node;
root>data = new data;
root->left_child = NULL;
root>right_child = NULL;
root-height = 0;
Ignou Study Helper-Sunil Poonia Page 15ges Too Srv Meee
‘[Link] NEY Suwit Poona
return root;
}
if{root--data left_child = insert(roat->left_child, new_data);
fi
11 Balance Factor Check Sooone
root >height = maxlget_height(root Ieft_child), get_height\root >right_child)) +1;
int b = get_balance_factor(root);
11 Checking if the node insertion results in Left heavy or Right heavy nodes.
if(o 4
11. Rotation Case
iflget_belance_factor(root-eft_chi
a
root = LL_rotation|root);
}
// LR Rotation Case
elsel
root->left_child = RR_rotation(root->left child);
root = LL_rotation(root);
}
else iff < -4}{
// RR Rotation Case
if(get_balance_factor(root->right_child)
root = RR_rotation(root);
}
Ignou Study Helper-Sunil Poonia Page 16geste Tonon Stvey Here
‘[Link] \ooit Suae Poona
// Rk Rotation Case
elsel
root->right_child = LL_rotation(root->right_child);
root = RR_rotation(root);
b et
return root;
int main()
{ avitree;
[Link]'= tree incert([Link], 10);
[Link] = [Link]{[Link], 20);
[Link] = tree insert([Link], 30);
cout << "Pre-order Traversal of the AVL Tree is
tree.pre_order([Link]);
return 0;
}
Output:
Pre-order Traversal of the AVL Tree is 20 10 30
Ignou Study Helper-Sunil Poonia Page 17