DAA Complete Notes
DAA Complete Notes
UNIT - 1
Introduction To Algorithm
1. Define algorithm?
1. Input: There are zero or more quantities, which are externally supplied.
3. Define debugging?
4. Define pseudocode?
s := 0.0;
for i := 1 to n do
s := s+ a[i];
return s;
Space for simple variable and fixed size variable is known as aggregate.
The value of the function increase or decrease as the n value increase. The
asymptotic behavior of a function is the study of how the value of a function
varies for large value of n of where n is the size of the input.
Worst-case:
Best-case:
UNIT - 2
Design And Analysis Of Algorithms
Types -
O - Big oh notation
1. O - Big oh notation :
Where t(n) and g(n) are non-negative functions defined on the set of
natural numbers.
Where t(n) and g(n) are non-negative functions defined on the set of
natural numbers.
Theta notation represents the upper and the lower bound of the running
time of an algorithm, it is used for analyzing the average-case complexity of
an algorithm.
A function t(n) is said to be in Θ(g(n)), if t(n) is bounded both above and
below by some constant multiple of g(n) for all large n, i.e if there exist
some positive constant c1 and c2 and some nonnegative integer n0 such
that,
Where t(n) and g(n) are non-negative functions defined on the set of
natural numbers.
A recursive algorithm calls itself with smaller input values and returns the result
for the current input by carrying out basic operations on the returned value for
the smaller input.
Set up sum expressing the no. of times the basic operation is executed.
(establishing order of growth).
count ←1
while n > 1 do
count ← count + 1
n←[n/2]
return count
10. Write the algorithm to find the largest element in a given array?
ALGORITHM -
MaxElement(A[0..n − 1])
maxval ← A[i]
return maxval
11. Write the algorithm to check whether all the elements in a given array are
distinct?
Algorithm -
UniqueElements(A{0...n-1)
//Output - Returns true if all the elements in A are distinct otherwise returns false.
if A[i] == A[j]
return false
return true
12. Write a recursive algorithm to find number of binary digits in a given decimal
integer?
Algorithm -
BinRec(n)
if n == 1 return 1
else return BinRec([n/2] + 1)
UNIT - 3
Brute Force & Exhaustive Search
It is very useful for solving small size instances of a problem, even though it
is inefficient.
2. Define selection sort and write a program to sort elements in array using
selection sort?
Selection sort is a simple and efficient sorting algorithm that works by repeatedly
selecting the smallest (or largest) element from the unsorted portion of the list
and moving it to the sorted portion of the list.
Algorithm -
SelectionSort(A[0...n-1])
//Sorts a given array by selection sort
min <- i
for j <- i +1 to n - 1 do
min <- j
3. Define bubble sort & write a program to sort elements in array using bubble
sort?
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping
the adjacent elements if they are in the wrong order. This algorithm is not suitable
for large data sets as its average and worst-case time complexity is quite high.
Algorithm -
BubbleSort(A[0...n-1])
Sequential search is the algorithm that starts at one end and goes through each
element of a list until the desired element is found, otherwise the search
continues till the end of the data set.
algorithm
algorithm
A graph is a collection of nodes (also called vertices) and edges (also called ores or
links) each connecting a pair of nodes.
Types -
1. Directed Graph :
Directed graph is a graph which consists of directed edges where each edge
in E is unidirectional.
2. Undirected Graph :
A cycle in a graph is a path in which first and last vertex are the same.
A directed graph is said to be acyclic when there is no cycle path in it. It is also
called as DAG(Directed Acyclic Graph).
Algorithm -
DFS (G)
//Input : Graph G = { V, E}
if v is marked with 0
dfs(v)
dfs(v)
count count + 1
if w is marked with 0
dfs(w)
The Breadth First Search (BFS) algorithm is used to search a graph data structure
for a node that meets a set of criteria. It starts at the root of the graph and visits
all nodes at the current depth level before moving on to the nodes at the next
depth level.
Applications of BFS -
Algorithm -
//implements BFS traversal of a given graph
//input: Graph G = { V, E}
count 0
if v is marked with 0
bfs(v)
bfs(v)
count count + 1
UNIT - 4
Decrease And Conquer
Divide And Conquer
Advantages -
Simplicity
Efficient algorithms
Problem-specific
Disadvantages -
Problem specific
Implementation complexity
To sort an array of size N in ascending order iterate over the array and compare
the current element (key) to its predecessor, if the key element is smaller than its
predecessor, compare it to the elements before. Move the greater elements one
position up to make space for the swapped element
Algorithm -
Insertionsort(A[0 ... n-1]) {
v <- A[i]
j <- i-1
j <- j - 1
A[j+1] <- V
Advantages -
Simple implementation
Efficient on small list of elements, on almost sorted list
Running time is linear in best case
It is a stable algorithm.
It is a in-place algorithm.
Time complexity -
Worst case - O(N^2)
Average case - O(N^2)
Best case - O(N)
4. What is divide and conquer? Give general plan for divide and conquer
Divide and conquer algorithm works by recursively breaking down a problem into
two or more sub-problems of the same (or related) type (divide), until these
become simple enough to be solved directly (conquer).
General plan -
A problem is divided into several subproblems of the same type, ideally of
about equal size.
The subproblems are solved (typically recursively, though sometimes a
different algorithm is employed, especially when subproblems become
small enough).
If necessary, the solutions to the subproblems are combined to get a
solution to the original problem.
5. Write an algorithm for finding the maximum and minimum?
Algorithm -
StraightMaxMin(a, n, max, min)
//Input: Array a[1..n]
//Output: Maximum (max) and minimum (min) values in the array
max := a[1] // Set max to the first element
min := a[1] // Set min to the first element
for i := 2 to n do:
if (a[i] > max) then:
max := a[i] // Update max if a[i] is greater
else
if (a[i] < min) then
min := a[i] // Update min if a[i] is smaller
Merge sort is defined as a sorting algorithm that SORT works by dividing an array
into smaller subarrays, sorting each subarray, and then merging the sorted
subarrays back together to form the final sorted array.
Algorithm -
MERGE_SORT(arr, low, end)
end of if
END MERGE_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.
Algorithm -
QUICKSORT (array A, start, end)
pivot = A[end]
i= start-1
then i = i + 1
}}
return i+1
Time Complexity -
Best case - O(n*logn)
Average case - O(n*logn)
Worst case - O(n2)
Advantages -
Parallelism - Divide and conquer algorithms tend to have a lot of inherent
parallelism.
Cache performance - Divide and conquer algorithms also tend to have good
cache performance.
Disadvantages -
Sometimes it can become more complicated than a basic iterative
approach.
Recursion is slow, which in some cases outweighs any advantages of this
divide and conquer process.
9. Define binary search? Write its algorithm
//Input - An array A[0 .. n-1] sorted in ascending order and a search key K
m <- (l+r)/2
if k = A[m]
return m
r <- m-1
return -1;
Traversal is a technique for visiting all of a tree's nodes and printing their values.
11. List and explain Types of Binary tree traversals ?
// t is a binary tree. Each node of t has three fields. lchild, data, and rchild.
if( t != 0) then
inorder(t->data);
// t is a binary tree. Each node of t has three fields. lchild, data, and rchild.
if( t != 0) then
preorder(t->data);
// t is a binary tree. Each node of t has three fields. lchild, data, and rchild.
if( t != 0) then
postorder(t->data);
Algorithm -
Height(t) {
UNIT - 5
Greedy Techniques
1. Prims Algorithm ?
Prim's Algorithm is a greedy algorithm that is used to find the minimum spanning
tree from a graph. Prim's algorithm finds the subset of edges that includes every
vertex of the graph such that the sum of the weights of the edges can be
minimized.
Prim's algorithm starts with the single node and explores all the adjacent nodes
with all the connecting edges at every step. The edges with the minimal weights
causing no cycles in the graph got selected.
How the prims algorithm works?
First, we have to initialize an MST with the randomly chosen vertex.
Now, we have to find all the edges that connect the tree in the above
step with the new vertices. From the edges found, select the minimum
edge and add it to the tree.
Repeat step 2 until the minimum spanning tree is formed.
Algorithm -
Step 1: Select a starting vertex
Step 2: Repeat Steps 3 and 4 until there are fringe vertices
Step 3: Select an edge 'e' connecting the tree vertex and fringe vertex that
has minimum weight
Step 4: Add the selected edge and the vertex to the minimum spanning tree
T
[END OF LOOP]
Step 5: EXIT
2. Kruskals Algorithm ?
Kruskal's Algorithm is used to find the minimum spanning tree for a connected
weighted graph. The main target of the algorithm is to find the subset of edges by
using which we can traverse every vertex of the graph.
It follows the greedy approach that finds an optimum solution at every stage
instead of focusing on a global optimum.
Now, take the edge with the lowest weight and add it to the spanning
tree. If the edge to be added creates a cycle, then reject the edge.
Continue to add the edges until we reach all vertices, and a minimum
spanning tree is created.
Algorithm -
Step 1: Create a forest F in such a way that every vertex of the graph is a
separate tree.
Step 2: Create a set E that contains all the edges of the graph.
Step 3: Repeat Steps 4 and 5 while E is NOT EMPTY and F is not spanning
Step 4: Remove an edge from E with minimum weight
Step 5:
IF the edge obtained in Step 4 connects two different trees, then add
it to the forest F (for combining two trees into one tree).
ELSE
Step 6: END
3. Dijkstra's Algorithm ?
Dijkstra's Algorithm is a Graph algorithm that finds the shortest path from a
source vertex to all other vertices in the Graph (single source shortest path).
The time complexity of Dijkstra's Algorithm is O(V2) with the help of the adjacency
matrix representation of the graph
Step 1:
First, we will mark the source node with a current distance of 0 and set the
rest of the nodes to INFINITY.
Step 2:
We will then set the unvisited node with the smallest current distance as
the current node, suppose X.
Step 3:
For each neighbor N of the current node X: We will then add the current
distance of X with the weight of the edge joining X-N. If it is smaller than the
current distance of N, set it as the new current distance of N.
Step 4:
Step 5:
We will repeat the process from 'Step 2' if there is any node unvisited left in
the graph.
distance[N] = INFINITY
previous[N] = NULL
distance[source_node] = 0
mark Q visited
temporary_distance = distance[Q] +
distance_between(Q, N)
distance[N] := temporary_distance
previous[N] := Q
Minimum spanning tree can be defined as the spanning tree in which the sum of
the weights of the edge is minimum.