Ads Unit-2
Ads Unit-2
Ads Unit-2
Graph
A Graph is a non-linear data structure consisting of vertices and edges. The
vertices are sometimes also referred to as nodes and the edges are lines or arcs
that connect any two nodes in the graph.
Representations of Graph
1. Adjacency Matrix
2. Adjacency List
Adjacency Matrix
Let’s assume there are n vertices in the graph So, create a 2D matrix adjMat[n]
[n] having dimension n x n.
If there is an edge from vertex i to j, mark adjMat[i][j] as 1.
If there is no edge from vertex i to j, mark adjMat[i][j] as 0.
Representation of Undirected Graph in Adjacency
Matrix:
Representation of directed Graph in Adjacency Matrix:
Adjacency List
Let’s assume there are n vertices in the graph So, create an array of list of
size n as adjList[n].
adjList[0] will have all the nodes which are connected (neighbour) to
vertex 0.
adjList[1] will have all the nodes which are connected (neighbour) to
vertex 1 and so on.
Undirected graph
directed graph
Graph traversals
Graph traversal refers to the process of visiting all the nodes (vertices) in a
graph in a systematic way. The two most common types of graph traversal
algorithms are:
1. Breadth-First Search (BFS):
2. Depth-First Search (DFS):
Partition Algorithm:
The partition algorithm rearranges the sub-arrays in a place.
PARTITION (array A, start, end)
{
pivot =A[end]
i = start-1
for j = start to end -1 {
if (A[j] < pivot) {
i=i+1
swap A[i] with A[j]
}
}
swap A[i+1] with A[end]
return i+1
}
Example
Sort word EXAMPLE in alphabetical order
Quick Sort Time Complexities
Merge Sort
It divides the given list into two equal halves, calls itself for the two halves and
then merges the two sorted halves. We have to define the merge() function to
perform the merging.
The sub-lists are divided again and again into halves until the list cannot be
divided further. Then we combine the pair of one element lists into two-
element lists, sorting them in the process and so on until we get the sorted list.
Algorithm
In the following algorithm, arr is the given array, beg is the starting element,
and end is the last element of the array.
MERGE_SORT(arr, beg, end)
{
if beg < end
{
mid = (beg + end)/2
MERGE_SORT(arr, beg, mid)
MERGE_SORT(arr, mid + 1, end)
MERGE (arr, beg, mid, end)
}
}
/* Function to merge the subarrays of a[] */
void merge(int a[], int beg, int mid, int end)
{
int i, j, k;
int n1 = mid - beg + 1;
int n2 = end - mid;
int LeftArray[n1], RightArray[n2]; //temporary arrays
/* copy data to temp arrays */
for (int i = 0; i < n1; i++)
LeftArray[i] = a[beg + i];
for (int j = 0; j < n2; j++)
RightArray[j] = a[mid + 1 + j];