Professional Documents
Culture Documents
Ds 4
Ds 4
A Graph is a non-linear data structure consisting of nodes and edges. The nodes are sometimes also referred to as
vertices and the edges are lines or arcs that connect any two nodes in the graph. More formally a Graph can be
defined as,
A Graph consists of a finite set of vertices (or nodes) and set of Edges which connect a pair of nodes
In the above Graph, the set of vertices V = {0, 1, 2, 3, 4} and the set of edges E = {01, 12, 23,
34, 04, 14, 13}.
Graph Terminology
Figure above shows a directed graph. In a directed graph, edges form an ordered pair. If there is an edge from A to B, then
there is a path from A to B but not from B to A. The edge (A, B) is said to initiate from node A (also known as initial node)
and terminate at node B (terminal node).
Regular graph It is a graph where each vertex has the same number of neighbours. That is, every node has the same
degree. A regular graph with vertices of degree k is called a k–regular graph or a regular graph of degree k. Figure below
shows regular graphs.
4. Multi graph
A multigraph is an undirected graph in which multiple edges (and sometimes loops) are allowed.
Multiple edges are two or more edges that connect the same two vertices. A loop is an edge (directed
or undirected) that connects a vertex to itself; it may be permitted or not.
5. Simple graph
A simple graph is an undirected graph in which both multiple edges and loops are disallowed as
opposed to a multigraph. In a simple graph with n vertices, every vertex’s degree is at most n-1.
6. Weighted and Unweighted graph
A weighted graph associates a value (weight) with every edge in the graph. We can also use words
cost or length instead of weight.
An unweighted graph does not have any value (weight) associated with every edge in the graph. In
other words, an unweighted graph is a weighted graph with all edge weight as 1. Unless specified
otherwise, all graphs are assumed to be unweighted by default.
7. Complete graph
A complete graph is one in which every two vertices are adjacent: all edges that could exist are
present.
8. Connected graph
A Connected graph has a path between every pair of vertices. In other words, there are no
unreachable vertices. A disconnected graph is a graph that is not connected.
Parallel Edges
a b c d
0 1 1 0
a
b 1 0 1 0
1 1 0 1
c
0 0 1 0
d
Adjacency Matrix of a Directed Graph
Let us consider the following directed graph and construct its adjacency matrix −
a b c d
0 1 1 0
a
0 0 1 0
b
c 0 0 0 1
0 0 0 0
d
There are two graph traversal techniques and they are as follows..
DFS algorithm in the data structure. It is a recursive algorithm to search all the
vertices of a tree data structure or a graph. The depth-first search (DFS) algorithm
starts with the initial node of graph G and goes deeper until we find the goal node or
the node with no children.
Because of the recursive nature, stack data structure can be used to implement the
DFS algorithm. The process of implementing the DFS is similar to the BFS algorithm.
The step by step process to implement the DFS traversal is given as follows -
We use the following steps to implement DFS traversal...
Step 1 - Define a Stack of size total number of vertices in the graph.
Step 2 - Select any vertex as starting point for traversal. Visit that vertex and
push it on to the Stack. Step 3 - Visit any one of the non-visited adjacent
vertices of a vertex which is at the top of stack and push it on to the stack.
Step 4 - Repeat step 3 until there is no new vertex to be visited from the vertex
which is at the top of the stack.
Step 5 - When there is no new vertex to visit then use back tracking and pop one vertex from the
stack.
Step 6 - Repeat steps 3, 4 and 5 until stack becomes Empty.
Step 7 - When stack becomes Empty, then produce final spanning tree by
removing unused edges from the graph
Back tracking is coming back to the vertex from which we reached the current
vertex.
Quick 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.
1. An array is divided into subarrays by selecting a pivot
element (element selected from the array).
Merge Sort
Merge sort is the sorting technique that follows the divide and conquer approach.
Merge sort is similar to the quick sort algorithm as it uses the divide and conquer
approach to sort the elements. It is one of the most popular and efficient sorting
algorithm. 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. The sorted two-element pairs is merged into the four-element
lists, and so on until we get the sorted list.
Let the elements of array are –
According to the merge sort, first divide the given array into two equal halves. Merge
sort keeps dividing the list into equal parts until it cannot be further divided.
As there are eight elements in the given array, so it is divided into two arrays of size
4.
Now, again divide these two arrays into halves. As they are of size 4, so divide them
into new arrays of size 2.
Now, again divide these arrays to get the atomic value that cannot be further divided.
In the next iteration of combining, now compare the arrays with two data values and
merge them into an array of found values in sorted order.
Now, there is a final merging of the arrays. After the final merging of above arrays,
the array will look like -
Program:
// Merge sort implementation
#include <stdio.h>
// Merge two subarrays L and M into arr
void merge(int a[], int low, int mid, int high)
{
// Create L ← A[low..mid] and M ← A[mid+1..high]
int n1 = mid - low + 1;
int n2 = high - mid;
int L[n1], M[n2];
for (int i = 0; i < n1; i++)
L[i] = a[low + i];
for (int j = 0; j < n2; j++)
M[j] = a[mid + 1 + j];
// Maintain current index of sub-arrays and main array
int i, j, k;
i = 0;
j = 0;
k = low;
// Until we reach either end of either L or M, pick larger among
// elements L and M and place them in the correct position at A[low..high]
while (i < n1 && j < n2) {
if (L[i] <= M[j]) {
a[k] = L[i];
i++;
}
else
{
a[k] = M[j];
j++;
}
k++;
}
// When we run out of elements in either L or M,
// pick up the remaining elements and put in A[low..high]
while (i < n1) {
a[k] = L[i];
i++;
k++;
}
while (j < n2) {
a[k] = M[j];
j++;
k++;
}
}
// Divide the array into two subarrays, sort them and merge them
void mergeSort(int a[], int l, int r) {
if (l < r) {
// m is the point where the array is divided into two subarrays
int m =( l + r) / 2;
mergeSort(a, l, m);
mergeSort(a, m + 1, r);
// Merge the sorted subarrays
merge(a, l, m, r);
}
}
The array A[0..5] contains two sorted subarrays A[0..3] and A[4..5]. Let us
see how the merge function will merge the two arrays.
void merge(int arr[], int low, int mid, int high) {
// Here, low = 0, mid = 4, high = 6 (size of array)
Step 1: Create duplicate copies of sub-arrays to be sorted
// Create L ← A[low..mid] and M ← A[mid+1..high]
int n1 = mid - low + 1 = 3 - 0 + 1 = 4;
int n2 = high - mid = 5 - 3 = 2;
int L[4], M[2];
for (int i = 0; i < 4; i++)
L[i] = a[p + i];
// L[0,1,2,3] = A[0,1,2,3] = [1,5,10,12]
This step would have been needed if the size of M was greater than L.
At the end of the merge function, the subarray A[p..r] is sorted.
Heap Sort
A heap is a complete binary tree, and the binary tree is a tree in which the node can have
the utmost two children. A complete binary tree is a binary tree in which all the levels except
the last level, i.e., leaf node, should be completely filled, and all the nodes should be left-
justified.
Heap sort processes the elements by creating the min-heap or max-heap using the elements
of the given array. Min-heap or max-heap represents the ordering of array in which the root
element represents the minimum or maximum element of the array.
Heap Sort Algorithm
To solve the problem follow the below idea:
First convert the array into heap data structure using heapify, then one by
one delete the root node of the Max-heap and replace it with the last node
in the heap and then heapify the root of the heap. Repeat this process until
size of heap is greater than 1.
Build a heap from the given input array.
Repeat the following steps until the heap contains only one
element:
Swap the root element of the heap (which is the largest
element) with the last element of the heap.
Remove the last element of the heap (which is now in the
correct position).
Heapify the remaining elements of the heap.
The sorted array is obtained by reversing the order of the elements
in the input array.
To understand heap sort more clearly, let’s take an unsorted array and try to
sort it using heap sort.
Consider the array: arr[] = {4, 10, 3, 5, 1}.
Build Complete Binary Tree: Build a complete binary tree from the array.
Transform into max heap: After that, the task is to construct a tree from
that unsorted array and try to convert it into max heap.
To transform a heap into a max-heap, the parent node should
always be greater than or equal to the child nodes
Here, in this example, as the parent node 4 is smaller
than the child node 10, thus, swap them to build a max-
heap.
Now, 4 as a parent is smaller than the child 5, thus swap both of
these again and the resulted heap and array should be like this:
Perform heap sort: Remove the maximum element in each step (i.e., move it
to the end position and remove that) and then consider the remaining
elements and transform it into a max heap.
Delete the root element (10) from the max heap. In order to delete
this node, try to swap it with the last node, i.e. (1). After removing
the root element, again heapify it to convert it into max heap.
Resulted heap and array should look like this:
Repeat the above steps and it will look like the following:
Now when the root is removed once again it is sorted. and the
sorted array will be like arr[] = {1, 3, 4, 5, 10}.
// Driver's code
int main()
{
int arr[100],i,N;
printf("enter size of array N:");
scanf("%d",&N);
printf("enter array elements:");
for(i=0;i<N;i++)
scanf("%d",&arr[i]);
// Function call
heapSort(arr, N);
printf("Sorted array is\n");
printArray(arr, N);
}