0% found this document useful (0 votes)
123 views

Assignment Advanced Data Structure and Algorithm: Group A

The document discusses the characteristics of an algorithm and provides examples. It then discusses the time complexity of merge sort as O(n log n) and defines recursion with an example of calculating factorial recursively. Finally, it states some key differences between trees and graphs such as trees having a parent-child relationship and graphs allowing self-loops.

Uploaded by

Nkj242089
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
123 views

Assignment Advanced Data Structure and Algorithm: Group A

The document discusses the characteristics of an algorithm and provides examples. It then discusses the time complexity of merge sort as O(n log n) and defines recursion with an example of calculating factorial recursively. Finally, it states some key differences between trees and graphs such as trees having a parent-child relationship and graphs allowing self-loops.

Uploaded by

Nkj242089
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Assignment

Advanced Data Structure And Algorithm

Group A
❑ State the characteristics of an algorithm.
 The word Algorithm means “a process or set of rules to be followed in
calculations or other problem-solving operations”. Therefore Algorithm
refers to a set of rules/instructions that step -by-step define how a work is
to be executed upon in order to get the expected results. An algorithm
should have the following characteristics –

Clear and Unambiguous: Algorithm should be clear and unambiguous. Each of its
steps should be clear in all aspects and must lead to only one meaning.
▪ Well-Defined Inputs: If an algorithm says to take inputs, it should be well-
defined inputs.

▪ Well-Defined Outputs: The algorithm must clearly define what output will be
yielded and it should be well-defined as well.

▪ Finite-ness: The algorithm must be finite, i.e. it should not end up in an infinite
loops or similar.

▪ Feasible: The algorithm must be simple, generic and practical, such that it can
be executed upon will the available resources. It must not contain some future
technology, or anything.

▪ Language Independent: The Algorithm designed must be language-


independent, i.e. it must be just plain instructions that can be implemented in
any language, and yet the
output will be same, as expected.
❑ What is the complexity of this merge sort algorithm?

 Merge Sort is quite fast, and has a time complexity of O(n*log n). It is also a
stable sort, which means the "equal" elements are ordered in the same order in
the sorted list. Hence the total time for mergeSort function will become n(log n
+ 1), which gives us a time complexity of O(n*log n).

Worst Case Time Complexity [ Big -O ]: O(n*log n)


Best Case Time Complexity [Big-omega]: O(n*log n)
Average Time Complexity [Big -theta]: O(n*log n)
Space Complexity: O(n)
• Time complexity of Merge Sort is O(n*Log n) in all the 3 cases (worst,
average and best) as merge sort always divides the array in two halves and
takes linear time to merge two halves.

• It requires equal amount of additional space as the unsorted array. Hence its
not at all recommended for searching large unsorted arrays.
• It is the best Sorting technique used for sorting Linked Lists.

❑ Define recursion? Give example.


 The process in which a function calls itself directly or indirectly is called
recursion and the corresponding function is called as recursive function. Using
recursive algorithm, certain problems can be solved quite easily.
Examples of such problems are Towers of Hanoi (TOH),
Inorder/Preorder/Postorder Tre e Traversals, DFS of Graph, etc.
In the following example, recursion is used to calculate the factorial of a number.

#include<stdio.h>
int fibonacci(int);
void main ()
{ int
n,f;
printf("Enter the value of
n?"); scanf("%d",&n); f =
fibonacci(n); printf("%d",f);
}
int fibonacci (int n)
{
if (n==0)
{
return 0;
}
Output else if (n == 1)
Enter the value of n?
12
4
return 1;
❑ State the basic difference between a tree and a graph.

Sr. Key Graph Tree


No.

1 Graph is the graphical On other hand Tree is also used


representation of nonlinear to represents the nonlinear data
Definition
data where data is denoted but in context of hierarchy where
by nodes and the relation data is again denoted by node
between them is denoted by and its successive data is
connecting path which is denoted by node just below it
known as Edge. termed as child nodes/s.
2 For representation of On other hand Tree is
Implementation nonlinear data Graph is implemented in such a manner
implemented in such a way that each node must have its
that the nodes may or may parent except Parent or first
not be connected or even node and must be connected to
there may be chances of some other node i.e no node
self-loops between nodes to could exist without other node.
represent the connection Also there is no chance of loop
between data. or self-loop in case of Tree as
data representation is in
hierarchical nature.
3 Data As Graph may contain self- On other hand in case of Tree the
Searching loop hence it is difficult to data is represented as nodes
search the data on traversal which are connected in
approach. User has to hierarchical manner so traversal
connect the dots to reach out search could be possible for user
the desired data. to search the desired data at
particular level of the tree.
4 As Graph did not represent On other hand in case of Tree
Parent
the data is hierarchical data is represented in hierarchical
Child
manner so there is no parent manner so parent to child relation
relation
child relation between data exists between the nodes and yes
representation hence no such there exist parent node as well as
parent node or child node do child node in case of Tree.
exist in case of Graph.
5 If cases of Graph we can say On other hand on case of Tree we
Vice e that all Graphs are not Trees. can say that All trees are Graphs.
Versa

6 Usage Main use of graphs is On other hand Main use of trees is


colouring and job scheduling. for sorting and traversing.

structure
❑ Define complete binary tree.
 A complete binary tree is a binary tree where each level ‘l’ except the
last has 2^l nodes and the nodes at the last level are all left aligned.
Complete binary trees are mainly used in heap based data
structures.
The nodes in the complete binary tree are inserted from left to right in
one level at a time.
If a level is full, the node is inserted in a new level.Below are some of the
complete binary trees.

❑ What do you understand by asymptotic notation?


 Asymptotic notation describes the algorithm efficiency and
performance in a meaningful way. It describes the behaviour of time
or space complexity for large instance characteristics.
The order of growth of the running time of an algorithm gives a
simple character of the
algorithm’s efficiency and also allows allow us to compare relative
performance of alternative algorithm. we call it gro wth function as
we ignore the very small constant. The asymptotic running time of
an algorithm is defined in terms of functions.

The asymptotic notation of an algorithm is classified into 3 types:


Big-O Notation (Ο) – Big O notation specifically describes worst case
scenario.
Omega Notation (Ω) – Omega(Ω) notation specifically describes best
case scenario.
Theta Notation (θ) – This notation represents the average complexity of
an algorithm
❑ What are applications of Stack?
 Expression Evaluation-
Stack is used to evaluate prefix, postfix and infix expressions.
Expression Conversion-
An expression can be represented in prefix, postfix or infix notation.
Stack can be used to convert one form of expression to another.
Syntax Parsing-
Many compilers use a stack for parsing the syntax of expressions,
program blocks etc. before translating into low level code.
Backtracking-
Suppose we are finding a path for solving maze problem. We choose a
path and after following it we realize that it is wrong. Now we need to go
back to the beginning of the path to start with new path. This can be
done with the help of stack.
Parenthesis Checking- Stack is used to check the proper opening and
closing of parenthesis.
String Reversal-
Stack is used to reverse a string. We push the characters of string one by
one into stack and then pop character from stack.
Function Call-
Stack is used to keep information about the active functions or
subroutines.
❑ What are the constraints of binary Search
 The major constraint of binary search is that there is a need of sorted
array to perform binary search operation.
If array is not sorted the output is either not correct or may be after a
long number of steps and according to data structure the output
should come in minimum number of steps.
❑ What is a pendent vertex in a graph?
 A vertex of a graph is said to be pendant if its neighborhood contains
exactly one vertex and only if it has a degree one.
a

b c

Here the vertex a and c are pendent vertex because their


degree is 1
❑ Define Dequeue.

 A deque, also known as a double-ended queue, is an ordered


collection of items similar to the queue. It has two ends, a front and a
rear, and the items remain positioned in the collection. And a de-
queue is kind of queue in which elements can be added or
removed from the either end but not from the middle . the term de-
queue is taken from double ended Q.

Group B

❑ Write an algorithm to search a given element in an


array using Binary Search

 Binary_Search(a,key,lb,ub) begin
Step 1: [initialization]
lb=0
ub=n-1;

Step 2: [search for the item] Repeat through step 4 while lower bound(lb)
is less than upper bound.

Step 3: [obtain the index of middle value] mid = (lb+ub)/2

Step 4: [compare to search for item] if(key &lt; a[mid]) then


ub=mid- otherwise if( key &gt; a[mid]) then
lb=mid+1; otherwise if(key==a[mid]) Write “match found” return
(mid) return Binary_Search(a,key,lb,ub)

Step 5: [unsuccessful search] Write “match not found”

Step 6: [end of algorithm]

❑ Differentiate between linear and non linear data


structures with suitable Example.

S.NO LINEAR DATA STRUCTURE NON-LINEAR DATA STRUCTURE

In a linear data structure, data


elements are arranged in a
linear order where each and In a non-linear data structure, data
1. every elements are attached to elements are attached in
its previous and next adjacent. hierarchically manner.

In linear data structure, single Whereas in non-linear data structure,


2. level is involved. multiple levels are involved.
Its implementation is easy
in comparison to non- While its implementation is complex
3.
linear data structure. in comparison to linear data structure.

In linear data structure, data While in non-linear data structure,


4. elements can be traversed in a data elements can’t be traversed in
single run only. a single run only.

In a linear data structure, memory While in a non-linear data structure,


5. is not utilized in an efficient way. memory is utilized in an efficient way.

Its examples are: array, stack, While its examples are: trees and
6. queue, linked list, etc. graphs.

Applications of linear Applications of non-linear data


data structures are mainly in structures are in Artificial
7. application software development. Intelligence and image processing.

❑ Write two algorithms to implement the PUSH ()


and POP () functions in stack.
 Push operation is used to insert an
element into stack.
PUSH_STACK(STACK,TOP,MAX,ITEM)

Algorithm to push an item into stack.

1) IF TOP = MAX then

Print “Stack is full”;


Exit;
2) Otherwise
TOP: = TOP + 1; /*increment TOP*/
STACK (TOP):= ITEM;
3) End of IF
4) Exit

Pop operation is used to remove an item from stack, first get the
element and then decrease TOP pointer.
POP_STACK(STACK,TO
P,ITEM)

Algorithm to pop an
element from stack.

1) IF TOP = 0 then
Print “Stack is
empty”;
Exit;
2) Otherwise
ITEM: =STACK
(TOP);
TOP:=TOP – 1;
3) End of IF

4) Exit

IS_FULL(STACK,TOP,M
AX,STATUS)

Algorithm to check
stack is full or not.
STATUS contains the
result status.

1) IF TOP = MAX then


STATUS:=true;
2) Otherwise
STATUS:=false;
3) End of IF
4) Exit

IS_EMPTY(STACK,TOP,
MAX,STATUS)

Algorithm to check
stack is empty or not.
STATUS contains the
result status.

1) IF TOP = 0 then
STATUS:=true;
2) Otherwise
STATUS:=false;
3) End of IF
4) Exit

❑ The inorder and priorder traversal of binary tree is given


below. Draw the tree and find its postorder traversal.
Inorder D B A E F C
Preorder A B D C E F

 Preorder = D B A E F C ( Root,Left,Right )

Inorder = ABDCEF ( Left,Root,Right )


D

B E

A C F
Postorder=A,B,C,F,E,D

❑ State the advantages and disadvantages of linked


list over array.
 Advantages of linked list over arrays:

• Arrays are bound by the limitation of their size. You have to specify
the number of elements in the array beforehand. Whereas in the
linked list you can add any number of elements.
• Suppose you have to insert any element at the beginning in an
array then you will have to shift all the elements one place right to
make room for the new element. This operation is expensive as it
takes O(n) time. Whereas you can insert any element at the
beginning in the linked list in O(1) time. Same is the case with
deletion of elements.
Disadvantage s of linked list over arrays:
• If the array is sorted you can apply binary search to search any
element. But even if linked list is sorted you cannot apply binary
search and so the complexity of searching in linked list is O(n).
• Extra memory space is required for the pointer with each element in
the linked list.
• Arrays have better cache locality than linked list which can greatly

affect it's performance.


❑ What is the time complexity of linear search
algorithm? Explain your answer.
Best case-
• In the best possible case,

• The element being searched may be found at the first position.


• In this case, the search terminates in success with just one
comparison.
• Thus in best case, linear search algorithm takes O(1) operations.
Worst Case-
In the worst possible case,
• The element being searched may be present at the last position or
not present in the array at all.
• In the former case, the search terminates in success with n
comparisons.
• In the later case, the search terminates in failure with n
comparisons.
• Thus in worst case, linear search algorithm takes O(n) operations
Thus, we have-

Time Complexity of Linear Search Algorithm is O(n).


Here, n is the number of elements in the linear array.

❑ Write an algorithm to implement quick sort to


arrange the elements of an array in ascending
order. Derived the complexity of this algorithm.
Algorithm

• Step 1 - Consider the first element of the list as pivot (i.e., Element
at first position in the list).
• Step 2 - Define two variables i and j. Set i and j to first and last
elements of the list respectively.

• Step 3 - Increment i until list[i] > pivot then stop.


• Step 4 - Decrement j until list[j] < pivot then stop.
• Step 5 - If i < j then exchange list[i] and list[j].
• Step 6 - Repeat steps 3,4 & 5 until i > j.
•Step 7 - Exchange the pivot element with list[j] element.
Complexity Analysis of Quick Sort

For an array, in which partitioning leads to unbalanced subarrays, to an


extent where on the left side there are no elements, with all the
elements greater than the pivot, hence on the right side.
And if keep on getting unbalanced subarrays, then the running time is the
worst case, which is O(n2 )
Where as if partitioning leads to almost equal subarrays, then the running
time is the best, with time complexity as O(n*log n).

Worst Case Time Complexity [


Big -O ]: O(n2) Best Case Time
Complexity [Big-omega]: O(n*log
n)
Average Time Complexity [Big-theta]: O(n*log n)

❑ What is a queue? Write separate algorithms for each of


the following queue functions, when a queue is
implemented using an array:
I. Test whether the queue is full.
II. Test whether the queue is empty.
III. Add an element into the queue
iv) Delete an element from the queue.

 A Queue is a linear structure that places elements in a


sequence, similar to a stack in which the first element is
inserted from one end called the REAR(also called tail),
and the removal of existing element takes place from the other
end called as FRONT(also called head).
This makes queue as FIFO(First in First Out) data structure, which
means that element inserted first will be removed first.

The process to add an element into queue is called Enqueue and the
process of removal of an element from queue is called Dequeue.

i). Queue is full :-

As we are using single dimension array to implement queue, we


just check for the rear pointer to reach at MAXSIZE to determine
that the queue is full. In case we maintain the queue in a circular
linked-list, the algorithm will differ. Algorithm of isfull() function −
Algorithm -
begin procedure isfull
if rear equals to MAXSIZE
return true
else
return false
endif
end procedure
ii). Queue is empty :-
Algorithm of isempty() function −

Algorithm- begin procedure isempty


if front is less than MIN OR front is greater than rear
return true
else
return false
endif
end procedure

If the value of front is less than MIN or 0, it tells that the queue is
not yet initialized, hence empty.

iii). Add an element in a queue :-


Check if the queue is already full by comparing rear to max - 1. if so,
then return an overflow error.
If the item is to be inserted as the first element in the list, in that case
set the value of front and rear to 0 and insert the element at the rear
end.
Otherwise keep increasing the value of rear and insert each element
one by one having rear as the index.

Algorithm-
Step 1: IF REAR = MAX - 1
Write OVERFLOW
Go to step
[END OF IF]
Step 2: IF FRONT = -1 and REAR = -1
SET FRONT = REAR = 0
ELSE
SET REAR = REAR + 1
[END OF IF]
Step 3: Set QUEUE[REAR] = NUM
Step 4: EXIT
iv). delete an element from the queue :-
If, the value of front is -1 or value of front is greater than rear , write an
underflow message and exit.
Otherwise, keep increasing the value of front and return the item stored at
the front end of the queue at each time.
Algorithm
Step 1: IF FRONT = -1 or FRONT > REAR
Write UNDERFLOW
ELSE
SET VAL = QUEUE[FRONT]
SET FRONT = FRONT + 1
[END OF IF]
Step 2: EXIT

❑ Write a n algorithm for insert a node and delete a


node from a single linked list. Consider also the
cases
i)empty list and ii) at any position in the list.

Inserting At Beginning of the list


We can use the following steps to insert a new node at beginning of the
single linked list...
• Step 1 - Create a newNode with given value.
• Step 2 - Check whether list is Empty (head == NULL)
• Step 3 - If it is Empty then, set newNode→next = NULL and head
= newNode.
• Step 4 - If it is Not Empty then, set newNode→next = head and
head = newNode.

Inserting At End of the list


We can use the following steps to insert a new node at end of the single
linked list...
• Step 1 - Create a newNode with given value and newNode →
next as NULL.
• Step 2 - Check whether list is Empty (head == NULL).
• Step 3 - If it is Empty then, set head = newNode.
• Step 4 - If it is Not Empty then, define a node pointer temp and
initialize with head.
• Step 5 - Keep moving the temp to its next node until it reaches to
the last node in the list (until temp → next is equal to NULL).
• Step 6 - Set temp → next = newNode.

Inserting At Specific location in the list (After a Node)


We can use the following steps to insert a new node after a node in the
single linked list...

• Step 1 - Create a newNode with given value.


• Step 2 - Check whether list is Empty (head == NULL)
• Step 3 - If it is Empty then, set newNode → next = NULL and
head = newNode.
• Step 4 - If it is Not Empty then, define a node pointer temp and
initialize with head.
• Step 5 - Keep moving the temp to its next node until it reaches to
the node after which we want to insert the newNode (until temp1 →
data is equal to location, here location is the node value after
which we want to insert the newNode).
• Step 6 - Every time check whether temp is reached to last node or
not. If it is reached to last node then display 'Given node is not
found in the list!!! Insertion not possible!!!' and terminate the
function. Otherwise move the temp to next node.
• Step 7 - Finally, Set 'newNode → next = temp → next' and 'temp
→ next = newNode'

Deleting from Beginning of the list


We can use the following steps to delete a node from beginning of the
single linked list...

• Step 1 - Check whether list is Empty (head == NULL)


• Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is
not possible' and terminate the function.
Deleting from Beginning of the list
• Step 3 - If it is Not Empty then, define a Node pointer 'temp' and
initialize with head.
• Step 4 - Check whether list is having only one node (temp → next
== NULL)
We can use the following steps to delete a node from beginning of
the single linked list...
• Step 5 - If it is TRUE then set head = NULL and delete temp
(Setting Empty list conditions)
• Step 6 - If it is FALSE then set head = temp → next, and delete
temp.
Deleting from End of the list
We can use the following steps to delete a node from end of the single
linked list...

• Step 1 - Check whether list is Empty (head == NULL)


• Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is
not possible' and terminate the function.
• Step 3 - If it is Not Empty then, define two Node pointers 'temp1'
and 'temp2' and initialize 'temp1' with head.
• Step 4 - Check whether list has only one Node (temp1 → next ==
NULL)
• Step 5 - If it is TRUE. Then, set head = NULL and delete temp1.
And terminate the function. (Setting Empty list condition)
• Step 6 - If it is FALSE. Then, set 'temp2 = temp1 ' and move temp1
to its next node. Repeat the same until it reaches to the last node in
the list. (until temp1 → next == NULL)
• Step 7 - Finally, Set temp2 → next = NULL and delete temp1.
Deleting a Specific Node from the list
We can use the following steps to delete a specific node from the single
linked list...

• Step 1 - Check whether list is Empty (head == NULL)


• Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is
not possible' and terminate the function.
• Step 3 - If it is Not Empty then, define two Node pointers 'temp1'
and 'temp2' and initialize 'temp1' with head.
• Step 4 - Keep moving the temp1 until it reaches to the exact node
to be deleted or to the last node. And every time set 'temp2 =
temp1' before moving the 'temp1' to its next node.
• Step 5 - If it is reached to the last node then display 'Given node
not found in the list! Deletion not possible!!!'. And terminate the
function.
• Step 6 - If it is reached to the exact node which we want to delete,
then check whether list is having only one node or not
• Step 7 - If list has only one node and that is the node to be deleted,
then set head = NULL and delete temp1 (free(temp1)).
• Step 8 - If list contains multiple nodes, then check whether temp1
is the first node in the list (temp1 == head).
• Step 9 - If temp1 is the first node then move the head to the next
node (head = head → next) and delete temp1.
• Step 10 - If temp1 is not first node then check whether it is last
node in the list (temp1 → next == NULL).
• Step 11 - If temp1 is last node then set temp2 → next = NULL and
delete temp1 (free(temp1)).
• Step 12 - If temp1 is not first node and not last node then set
temp2 → next = temp1 → next and delete temp1 (free(temp1)).

You might also like