You are on page 1of 25

2020

Data Structures. &


Algorithms Assignment
2K19/ITE/10
ALI AHMED
What is data-structure and list studied data-structures?
In computer science, a data structure is a data organization, management and
storage format that enables efficient access and modification. More precisely, a
data structure is a collection of data values, the relationships among them, and he
function or operations that can be applied to the data.

What is linked list and enlist types of linked list?


In computer science, a linked list is a linear collection of data elements whose
order is not given by their physical placement in memory, instead, each element
points to the next. It is a data structure consisting of a collection of nodes which
together represent a sequence.
● Simple Linked List − Item navigation is forward only.
● Doubly Linked List − Items can be navigated forward and backward.
● Circular Linked List − Last item contains link of the first element as next
and the first element has a link to the last element as previous.

What is stack and which operations can be performed?


In computer science, a stack is an abstract data type that serves as a collection of
elements, with two main principal operations: push, which adds an element to
the collection, and pop, which removes the most recently added element that
was not yet removed.
Operations:
A stack is used for the following two primary operations −
● push() − Pushing (storing) an element on the stack.
● pop() − Removing (accessing) an element from the stack.
Push Operation:
The process of putting a new data element onto stack is known as a Push
Operation. Push operation involves a series of steps −
1) Checks if the stack is full.
2) If the stack is full, produces an error and exit.
3) If the stack is not full, increments top to point next empty space.
4) Adds data element to the stack location, where top is pointing.
5) Returns success.
Algorithm for PUSH Operation:
begin procedure push: stack, data

if stack is full
return null
endif

top ← top + 1
stack[top] ← data

end procedure
Pop Operation:
Accessing the content while removing it from the stack, is known as a Pop
Operation. In an array implementation of pop() operation, the data element is not
actually removed, instead top is decremented to a lower position in the stack to
point to the next value. But in linked-list implementation, pop() actually removes
data element and deallocates memory space.
A Pop operation may involve the following steps −
1) Checks if the stack is empty.
2) If the stack is empty, produces an error and exit.
3) If the stack is not empty, accesses the data element at which top is pointing.
4) Decreases the value of top by 1.
5) Returns success.
Algorithm for Pop Operation:
begin procedure pop: stack

if stack is empty
return null
endif

data ← stack[top]
top ← top - 1
return data

end procedure

To use a stack efficiently, we need to check the status of stack as well. For the same
purpose, the following functionality is added to stacks −
● peek() − get the top data element of the stack, without removing it.
● isFull() − check if stack is full.
● isEmpty() − check if stack is empty.

Algorithm of peek() function:


begin procedure peek
return stack[top]
end procedure

Algorithm of isfull() function:


begin procedure isfull

if top equals to MAXSIZE


return true
else
return false
endif
end procedure

Algorithm of isempty() function:


begin procedure isempty

if top less than 1


return true
else
return false
endif

end procedure

Explain difference between linear searching and binary search?


Definition of Linear Search:
Linear search is an algorithm to find an element is a list by sequentially checking
the elements of the list until finding the matching element. Binary search is an
algorithm that finds the position of a target value within a sorted array. Thus, this
is the main difference between linear search and binary search.

Definition of Binary Search:


Binary search is an extremely efficient algorithm. This search technique consumes
less time in searching the given item in minimum possible comparisons. To do the
binary search, first, we have to sort the array elements.
Important Differences:
● Input data needs to be sorted in Binary Search and not in Linear Search
● Linear search does the sequential access whereas Binary search access data
randomly.
● Time complexity of linear search -O(n), Binary search has time complexity
O(log n).
● Linear search performs equality comparisons and Binary search performs
ordering comparisons

BASIS FOR
LINEAR SEARCH BINARY SEARCH
COMPARISON

Time Complexity O(N) O(log 2 N)

Best case time First Element O(1) Center Element O(1)

Prerequisite for an No required Array must be in sorted order


array

Worst case for N N comparisons are Can conclude after only log2N
number of elements required comparisons

Can be implemented Array and Linked list Cannot be directly implemented


on on linked list

Insert operation Easily inserted at the end Require processing to insert at


of list its proper place to maintain a
sorted list.

Algorithm type Iterative in nature Divide and conquer in nature

Usefulness Easy to use and no need Anyhow tricky algorithm and


for any ordered elements should be organized in
elements. order.
Lines of Code Less More

Conclusion:
Both linear and binary search algorithms can be useful depending on the
application. When an array is the data structure and elements are arranged in
sorted order, then binary search is preferred for quick searching. If linked list is
the data structure regardless how the elements are arranged, linear search is
adopted due to unavailability of direct implementation of binary search
algorithm.

What is insertion sort and how insertion sort works?


Insertion sort is a simple sorting algorithm that builds the final sorted array one
item at a time. It is much less efficient on large lists than more advanced
algorithms such as quicksort, heapsort, or merge sort

What is merge sort and how it works?


In computer science, merge sort is an efficient, general-purpose, comparison
based sorting algorithm. Most implementations produce a stable sort, which
means that the order or equal elements is the same in the input and output.
Merge sort is a divide and conquer algorithm that was invented by John von
Neumann in 1945
What is bubble sort and how bubble sort works?
Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm
that repeatedly steps through the list, compares adjacent elements and swaps
them if they are in the wrong order. The pass through the through list is repeated
until the list is sorted. Bubble sort is used when complexity of the code does not
matter or a short code is preferred. This algorithm is not suitable for large data
sets as its average and worst case complexity are of Ο(n2) where n is the number
of items.
Example:
Take an unsorted array for an example. Bubble sort takes Ο(n2) time so we're
keeping it short.
14 33 24 35 10
Bubble sort starts with very first two elements, comparing them to check which
one is greater.
14 33 27 35 10
In this case, value 33 is greater than 14, so it is already in sorted locations. Next,
we compare 33 with 27.
14 33 27 35 10

We find that 27 is smaller than 33 and these two values must be swapped.
14 33 27 35 10
The new array should look like this
14 27 33 35 10
Next we compare 33 and 35. We find that both are in already sorted positions.
14 27 33 35 10
Then we move to the next two values, 35 and 10.
14 27 33 35 10
We know then that 10 is smaller 35. Hence they are not sorted.
14 27 33 35 10
We swap these values. We find that we have reached the end of the array. After
one iteration, the array should look like this
14 27 33 10 35
After the second iteration, it should look like this
14 27 10 33 35
Notice that after each iteration, at least one value moves at the end.
14 10 27 33 35

And when there's no swap required, bubble sorts learns that an array is
completely sorted.

14 14 27 33 35

Bubble Sort Algorithm:

bubbleSort(array)

for i <- 1 to indexOfLastUnsortedElement-1

if leftElement > rightElement

swap leftElement and rightElement

end bubbleSort
What is a queue in data-structure and which operations can be performed?
In computer science, a queue is a collection of entities that are maintained in a
sequence and can be modified by the addition of entities at one end of the
sequence and the removal of entities from the other end of the sequence.

How insertion sort and selection sorts are different?


Sorting is a basic operation in which the elements of an array is arranged in some
specific order to enhance its searchability. In simple words, the data is sorted so
that it could be easily searched.

BASIS FOR
INSERTION SORT SELECTION SORT
COMPARISON

Basic The data is sorted by inserting the The data is sorted by selecting and
data into an existing sorted file. placing the consecutive elements in
sorted location.

Nature Stable Unstable

Process to be Elements are known beforehand Location is previously known while


followed while location to place them is elements are searched.
searched.

Immediate data Insertion sort is live sorting It cannot deal with immediate data, it
technique which can deal with needs to be present at the beginning.
immediate data.
Best case O(n) O(n2)
complexity

Conclusion:
Among both sorting algorithm, the insertion sort is fast, efficient, stable while
selection sort only works efficiently when the small set of elements is involved or
the list is partially previously sorted. The number of comparisons made by
selection
sort is greater than the movements performed whereas in insertion sort the
number of times an element is moved or swapped is greater than the
comparisons made.

Differentiate depth first traversal and breadth first traversal?


BFS stands for Breadth First Search is a vertex based technique for finding a
shortest path in graph. It uses a Queue data structure which follows first in first
out. In BFS, one vertex is selected at a time when it is visited and marked then its
adjacent are visited and stored in the queue. It is slower than DFS.
Example:
A
/ \
B C
/ / \
D E F
Output is:
A, B, C, D, E, F

DFS stands for Depth First Search is an edge based technique. It uses the Stack
data structure, performs two stages, first visited vertices are pushed into stack
and second if there are no vertices then visited vertices are popped.
Example:
A
/ \
B C
/ / \
D E F
Output is:
A, B, D, C, E, F

1. BFS stands for Breadth First Search. DFS stands for Depth First Search.

BFS(Breadth First Search) uses Queue data DFS(Depth First Search) uses Stack data
2. structure for finding the shortest path. structure.

BFS can be used to find single source shortest


path in an unweighted graph, because in BFS,
we reach a vertex with minimum number of In DFS, we might traverse through more edges
3. edges from a source vertex. to reach a destination vertex from a source.
BFS is more suitable for searching vertices DFS is more suitable when there are solutions
3. which are closer to the given source. away from source.

DFS is more suitable for game or puzzle


BFS considers all neighbors first and therefore problems. We make a decision, then explore
not suitable for decision making trees used in all paths through this decision. And if this
4. games or puzzles. decision leads to win situation, we stop.

The Time complexity of BFS is O(V + E) when The Time complexity of DFS is also O(V + E)
Adjacency List is used and O(V^2) when when Adjacency List is used and O(V^2) when
Adjacency Matrix is used, where V stands for Adjacency Matrix is used, where V stands for
5. vertices and E stands for edges. vertices and E stands for edges.

What is selection sort and how selection sort works?


Definitions
The Selection sort perform sorting by searching for the minimum value number
and placing it into the first or last position according to the order (ascending or
descending). The process of searching the minimum key and placing it in the
proper position is continued until the all the elements are placed at right position.

Working of the Selection Sort


● Suppose an array ARR with N elements in the memory.
● In the first pass, the smallest key is searched along with its position then
the ARR[POS] is swapped with ARR[0]. Therefore, ARR[0] is sorted.
● In the second pass, again the position of the smallest value is determined in
the subarray of N-1 elements. Interchange the ARR[POS] with ARR[1].
● In the pass N-1, the same process is performed to sort the N number of
elements.
Example:
0 1 2 3 4
17 16 3 13 6

Pass 1 17 16 3 13 6

⬆ ⬆
Min Loc
Pass 2 3 16 17 13 6

⬆ ⬆
Min Loc
Pass 3 3 6 17 13 16

⬆ ⬆
Min Loc
Pass 4 3 6 13 17 16

⬆ ⬆
Min Loc
Pass 5 3 6 13 16 17
What is difference between tree and graph?
Definition of Tree
A tree is a finite collection of data items usually termed as nodes. As it is
mentioned above that a tree is a non-linear data structure which arranges data
items in sorted order. It is used to show a hierarchical structure between the
various data elements and organizes the data into branches which relate the
information. The addition of a new edge in a tree results in a formation of the
loop or circuit. There are several types of trees such as a binary tree, binary
search tree, AVL tree, threaded binary tree, B-tree, etc.

Properties of tree:

● There is designated node at the top of the tree known as a root of the tree.

● The remaining data items are divided into disjoint subsets refer to as
subtree.

● The tree is expanded in height towards the bottom.

● A tree must be connected which means there must be a path from one root
to all other nodes.

● It does not contain any loops.

● A tree has n-1 edges.

Definition of Graph:

A graph is also a mathematical non-linear data structure which can represent


various kinds of physical structure. It consists of a group of vertices (or nodes) and
set of edges that connect the two vertices. Vertices on the graph is represented as
point or circles and edges are shown as arcs or line segments. An edge is
represented by E(v,w) where v and w are the pairs of vertices. Removal of an edge
from a circuit or connected graph creates a subgraph that is a tree.
The graphs are classified into various categories such as directed, non-directed,
connected, non-connected, simple and multi-graph
Properties of a graph:

● A vertex in a graph can be connected to any number of other vertices using


edges.
● An edge can be bidirected or directed.
● An edge can be weighted.

BASIS FOR
TREE GRAPH
COMPARISON

Path Only one between two More than one path is allowed.
vertices.

Root node It has exactly one root Graph doesn't have a root node.
node.

Loops No loops are permitted. Graph can have loops.

Complexity Less complex More complex comparatively


Traversal techniques Pre-order, In-order and Breadth-first search and depth-
Post-order. first search.

Number of edges n-1 (where n is the number Not defined


of nodes)

Model type Hierarchical Network

Conclusion:
Graph and tree are the non-linear data structure which is used to solve various
complex problems. A graph is a group of vertices and edges where an edge
connects a pair of vertices whereas a tree is considered as a minimally connected
graph which must be connected and free from loops.

What is Fibonacci Series and write a program of Fibonacci Series?


Leonardo Pisano Boglio (aka Leonardo Fibonacci) was an Italian Mathematician
during the Middle Ages (c. 1170 - 1250) who wrote the book "Liber Abaci," which
is a book based on mathematical calculations. Of course, the most famous
algorithm in the book is the Fibonacci sequence
In academia, computer science programming courses like to use this algorithm in
their study of recursive methods. In C.S., a recursive method is a method that is
being defined within its own definition. Basically, instead of the method being
called by another method, it calls itself. Which in its own way makes it another
way to program a loop.
1. #include <iostream>
2. using namespace std;
3. int main() {
4. int n1=0,n2=1,n3,i,number;
5. cout<<" how many terms of series you want to see: ";
6. cin>>number;
7. cout<<n1<<" "<<n2<<" "; //printing 0 and 1
8. for(i=2;i<number;i++) //loop starts from 2 because 0 and 1 are already printed
9. {
10. n3=n1+n2;
11. cout<<n3<<" ";
12. n1=n2;
13. n2=n3;
14. }
15. return 0; }
OUTPUT:
1. how many terms of series you want to see : 7
2. 0 1 1 2 3 5 8
What is an algorithm and why we need to do algorithm analysis?
Probably the best way to understand an algorithm is to think of it as a recipe.
There are many ways to bake cookies, but by following a recipe a baker knows to
first preheat the oven, then measure out the flour, add butter, chocolate chips,
etc. until the desired cookies are complete.
Using algorithms, a programmer or computer scientist can tell his machine to
query database A for last month’s sales figures, compare them to the prior month
and the same month last year, and then display it in a bar graph.
Mix multiple algorithms together and you have a working computer program.
As can be expected, there are numerous types of algorithms for virtually every
kind of mathematical problem there is to solve. There are:
● Numerical algorithms.
● Algebraic algorithms.
● Geometric algorithms.
● Sequential algorithms.
● Operational algorithms.
● Theoretical algorithms.
Algorithms named after mathematicians
● Shor’s algorithm.
● Girvan-Newman algorithm.
● Several Euclidian algorithms.
Algorithms named after the specific problem they solve
● Bidirectional search algorithm.
● K-way merge algorithm.
In the computing field, most algorithms tend to solve data management and
analysis problems.
Top Computing Algorithms:
(According to Ohio State University)
• Sort
Arranging data in an efficient and useful manner. These include quick sort, merge
sort, counting sort and others.
• Search
Finding key data in sorted data sets. The most common is the binary sort, but
there is also depth, breadth and first searches used by web applications.
• Hashing
Similar to search but with an indexing and key ID component. Hashing provides
superior results because it assigns a key to certain data.
• Dynamic Programming
Converts larger, complex problems into series of smaller problems.
• Exponential by Squaring (EbS)
Also known as binary exponentiation, EbS speeds up the calculation of large
integers, polynomials, square matrices, and other complex problems.
String Matching and Parsing:
Designed to find patterns in large data sets using predefined terms and restrictions.
• Primality Testing
Determines prime numbers either deterministically or probabilistically; mostly
used in cryptography.
• Analysis of Algorithms
Analysis of algorithm is the process of analyzing the problem-solving capability of
the algorithm in terms of the time and size required (the size of memory for
storage while implementation). However, the main concern of analysis of
algorithms is the required time or performance. Generally, we perform the
following types of analysis −
● Worst-case − The maximum number of steps taken on any instance of size a.
● Best-case − The minimum number of steps taken on any instance of size a.
● Average case − An average number of steps taken on any instance of size a.
● Amortized − A sequence of operations applied to the input of size a averaged
over time.
To solve a problem, we need to consider time as well as space complexity as the
program may run on a system where memory is limited but adequate space is
available or may be vice-versa. In this context if we compare bubble
sort and merge sort. Bubble sort does not require additional memory, but merge
sort requires additional space. Though time complexity of bubble sort is higher
compared to merge sort, we may need to apply bubble sort if the program needs
to run in an environment, where memory is very limited.
List three examples of divide and conquer algorithms?
1. Binary Search:
A searching algorithm. In each step, the algorithm compares the input
element x with the value of the middle element in the array. If the values
match, return the index of the middle. Otherwise, if x is less than the
middle element, then the algorithm recurs for the left side of the middle
element, else recurs for the right side of the middle element.

2. Quicksort:
A sorting algorithm. The algorithm picks a pivot element, rearranges the
array elements in such a way that all elements smaller than the picked
pivot element move to the left side of pivot, and all greater elements move
to the right side. Finally, the algorithm recursively sorts the subarrays on
the left and right of the pivot element.

3. Merge Sort:
A sorting algorithm. The algorithm divides the array in two halves,
recursively sorts them, and finally merges the two sorted halves.

What is a spanning tree and how can we find no. of spanning trees in a
graph?

In the mathematical field of graph theory, a spanning tree T of an undirected graph


G is a subgraph that is a tree which includes all the vertices of G, with a minimum
possible number of edges. In general, a graph may have several spanning trees, but
a graph that is not connected will not contain a spanning tree.

If a graph is a complete graph with n vertices, then total number of spanning trees
is n(n-2) where n is the number of nodes in the graph. In complete graph, the task is
equal to counting different labeled trees with n nodes for which have.
If graph is not complete follow the given procedure
1. Create Adjacency Matrix for the given graph.
2. Replace all the diagonal elements with the degree of nodes. For example.
element at (1,1) position of adjacency matrix will be replaced by the degree
of node 1, element at (2,2) position of adjacency matrix will be replaced by
the degree of node 2, and so on.
3. Replace all non-diagonal 1’s with -1.
4. Calculate co-factor for any element.
5. The cofactor that you get is the total number of spanning tree for that
graph.

Consider the following graph:

Adjacency Matrix for the above graph will be as follows

1 2 3 4
1 0 0 1 1
2 0 0 1 1
3 1 1 0 1
4 1 1 1 0
After applying STEP 2 and STEP 3, adjacency matrix will look like

1 2 3 4
1 2 0 -1 -1
2 0 2 -1 -1
3 -1 -1 3 -1
4 -1 -1 -1 3

Number of Spanning Trees=Cofactor of any element in Laplacian Matrix

Ci j = (-1) i+j |Mi j

C11= (-1)2(2(3*3(-1)) -(-1) (-3-1) +(-1) (1+3)) =8


1 2 3 4
1 2 0 -1 -1
2 0 2 -1 -1
3 -1 -1 3 -1
4 -1 -1 -1 3

C14= (-1)5*(0-(2) (1+3) +(-1) (1-1)) =8


1 2 3 4
1 2 0 -1 -1
2 0 2 -1 -1
3 -1 -1 3 -1
4 -1 -1 -1 3
What is difference between tree and graph?
Graph Tree
Graph is a non-linear data structure. Tree is a non-linear data structure.
It is a collection of vertices/nodes and edges. It is a collection of nodes and edges.

It is a collection of vertices/nodes and edges. General trees consist of the nodes having any
number of child nodes. But in case of binary
trees every node can have at the most two child
nodes.

There is no unique node called root in graph. There is a unique node called root in trees.

A cycle can be formed. There will not be any cycle.

Applications: For game trees, decision trees, the


tree is used.
Applications: For finding shortest path in

networking graph is used.

Graph and tree are the non-linear data structure which is used to solve various
complex problems. A graph is a group of vertices and edges where an edge
connects a pair of vertices whereas a tree is considered as a minimally connected
graph which must be connected and free from loops.

What are linear data structure and list common operations of data-
structures?
Linear Data Structure:
Data structure where data elements are arranged sequentially or linearly where
the elements are attached to its previous and next adjacent in what is called
a linear data structure. In linear data structure, single level is involved. Therefore,
we can traverse all the elements in single run only. Linear data structures are easy
to implement because computer memory is arranged in a linear way. Its examples
are array, stack, queue, linked list, etc.
Common operations performed on a data structure are
• Insertion:
add items to it.
• Deletion:
to remove items from it.
• Modification:
to modify items.
• Searching:
to search for a particular item.
• Sorting:
to sort the items in a required order.
Explain difference between single and double linked list
Both Singly linked list and Doubly linked list are the implementation of Linked list
in which every element of singly linked list contains some data and a link to the
next element, which allows to keep the structure. On the other hand, every node
in a doubly linked list also contains a link to the previous node.
Singly linked list Doubly linked list
Singly linked list allows traversal Doubly linked list allows element two-
elements only in one way. way traversal.
Singly linked list is generally used for On other hand doubly linked list can
implementation of stacks be used to implement stacks as well as
heaps and binary trees.
As singly linked list store pointer of On other hand Doubly linked list uses
only one node so consumes lesser more memory per node (two
memory. pointers).

You might also like