Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit 05 DS

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 27

UNIT-05

C with Data Structures-BSc


Graphs, Searching and
Sortings

Q. Define Graph and write in detail on graph


terminology Graph :
• Graph is a non linear data structure; it contains a set of points known as nodes (or vertices) and set
of links known as edges (or Arcs) which connects the vertices.
• Generally, a graph G is represented as G = (V , E ), where V is set of vertices and E is set of edges.
• The following is a graph with 5 vertices and 6 edges. This graph G can be defined as
• G = ( V , E ) Where V = {A,B,C,D,E} and
• E = {(A,B),(A,C)(A,D),(B,D),(C,D),(B,E),(E,D)}.

The picture above represents the following graph:

➢ V = {1,2,3,4,5,6}

➢ E = {{1,2},{1,5},{2,3},{2,5},{3,4},{4,5},{4,6}}

Graph Terminology

Vertex and Edge :


Each node of the graph is represented as a vertex. The labeled circle
represents vertices. Thus, A to D are vertices. • Edge − Edge represents
a path between two vertices or a line between two vertices.
Adjacent Nodes:
Two nodes or vertices are adjacent if they are connected to each other
through an edge. In the example, B is adjacent to A, C is adjacent to
A, and so on.
Loop:
• In a directed graph some edges may connect to itself then
such type of edges are called as a loop.

In the figure, (A, A) is a loop.


Undirected Graph :
A Graph that does not contain any direction is called as undirected graph.

Directed Graph:
A pair of vertices between the edges must be ordered then that graph
is known as directed graph

Weighted Graph :
Some graphs contain weights on their edges, such type of graphs is called
as weighted graph and the number associated with an edge is called as
weight.
 The weight of an edge is often referred to as the "cost" of the edge.
 In applications, the weight may be a measure of the length of a
route, the capacity of a line, the energy required to move between
locations along a route, etc.
Complete graph :
• A graph in which every vertex is directly connected to every other
vertex.
Path :
A path in a graph represents a way to get from an origin to a destination by
traversing edges in the graph. For example, in the undirected graph G=(V,E)
drawn below, there are many paths from node 6 to node 1.

Isolated Node:
In a graph if a node that does not adjacent to any other node then that node
is called as an isolated node.
Null Graph
•The graph containing only isolated nodes is called as a Null graph.

Cyclic Graph and Acyclic Graph


A path from a node to itself is called as a cyclic graph. In other
words, a graph containing a cycle in it is called as a cyclic
graph.
The graph does not contain the cycle is called as an acyclic
graph and the directed graph that does not contain any cycle is
called as directed acyclic graph.
In-degree and Out-degree
In-degree of a node:
The In-degree of a node n is nothing but the number of
edge coming to that node.
Out-Degree of a node:
The out-degree of a node n is nothing but the number
of edges that are move away from that node.

Q. Explain in detail on how can we represent a Graph?


A graph representation is a technique to store graph into the memory of computer.
To represent a graph, we just need the set of vertices and for each vertex the neighbors of the vertex (vertices
which is directly connected to it by an edge). If it is a weighted graph, then the weight will be associated with
each edge.
Graph data structure is represented using following representations...
1. Adjacency Matrix
2. Incidence Matrix
3. Adjacency List
1. Adjacency Matrix
In this representation, graph can be represented using a matrix of size total number of vertices by total number
of vertices. That means if a graph with 4 vertices can be represented using a matrix of 4X4 class. In this
matrix, rows and columns both represent vertices. This matrix is filled with either 1 or 0. Here, 1 represents
there is an edge from row vertex to column vertex and 0 represents there is no edge from row vertex to
column vertex.

2. Incidence Matrix
 In this representation, graph can be represented using a matrix of size total number of vertices by total
number of edges. That means if a graph with 4 vertices and 6 edges can be represented using a matrix
of 4X6 class.
 In this matrix, rows represent vertices and columns represent edges.
 This matrix is filled with either 0 or 1 or -1.
 Here, 0 represents row edge is not connected to column vertex, 1 represents row edge is connected as
outgoing edge to column vertex and -1 represents row edge is connected as incoming edge to column
vertex.

3. Adjacency List
• In this representation, every vertex of graph contains list of its adjacent vertices. For example,
consider the following directed graph representation implemented using linked list.
Q. What is Graph Traversal? Explain different Graph Traversal
techniques. Graph Traversal:
Graph traversal is technique used for searching a vertex in a graph. The graph traversal is also used to decide
the order of vertices to be visit in the search process. A graph traversal finds the edges to be used in the search
process without creating loops that means using graph traversal we visit all vertices of graph without getting
into looping path. There are two graph traversal techniques and they are as follows...
1. DFS (Depth First Search)
2. BFS (Breadth First Search)

1. DFS (Depth First Search)


DFS traversal of a graph, produces a spanning tree as final result. Spanning Tree is a graph
without any loops. We use Stack data structure with maximum size of total number of vertices in the graph to
implement DFS traversal of a graph. 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 adjacent vertex of the vertex which is at top of the stack which is not
visited and push it on to the stack.
Step 4: Repeat step 3 until there are no new vertex to be visit from the vertex on top of the stack.
Step 5: When there is no new vertex to be 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 came to current vertex.
2.BFS (Breadth First Search)

BFS traversal of a graph, produces a spanning tree as final result. Spanning Tree is a graph

without any loops. We use Queue data structure with maximum size of total number of vertices in the graph

to implement BFS traversal of a graph.

We use the following steps to implement BFS traversal...

Step 1: Define a Queue of size total number of vertices in the graph.

Step 2: Select any vertex as starting point for traversal. Visit that vertex and insert it into the Queue.

Step 3: Visit all the adjacent vertices of the vertex which is at front of the Queue which is not visited and

insert them into the Queue

Step 4: When there is no new vertex to be visit from the vertex at front of the Queue then delete that vertex

from the Queue.

Step 5: Repeat step 3 and 4 until queue becomes empty.

Step 6: When queue becomes Empty, then produce final spanning tree by removing unused edges from the

graph
SEARCHINGS AND SORTINGS

Q. Define Searching. Explain Linear Search(Sequential Search) with an example.


Searching
⚫ Search is a process of finding a value in a list of values.
⚫ In other words, searching is the process of locating given value position in a list of values.
⚫ It decides whether a search key is present in the data or not.
⚫ It can be done on internal data structure or on external data structure.
⚫ Searching Algorithms are designed to check for an element or retrieve an element from any
data structure where it is stored.
Linear Search Algorithm (Sequential Search Algorithm)
Linear search algorithm finds given element in a list of elements with O(n) time complexity where n is total
number of elements in the list. Linear search is implemented using following steps...
1: Read the search element from the user
2: Compare, the search element with the first element in the list.
3: If both are matching, then display "Given element found!!!" and terminate the function
4: If both are not matching, then compare search element with the next element in the list.
5: Repeat steps 3 and 4 until the search element is compared with the last element in the list.
6: If the last element in the list is also doesn't match, then display "Element not found!!!" and terminate the
function.
Example
Write a program on Linear Search
/* Linear Search*/
#include <stdio.h>
#include<conio.h>
void main()
{
int a[100], search, i, n;
clrscr();

printf("Enter number of elements in array\n");


scanf("%d", &n);

printf("Enter %d integer(s)\n", n);


for (i = 0; i < n; i++)
scanf("%d", &a[i]);

printf("Enter a number to search\n");


scanf("%d", &search);

for (i = 0; i < n; i++)


{
if (a[i] == search)
{
printf("%d is present at location %d.\n", search, i+1);
break;
}
}
if (i == n)
printf("%d is not present in the array.\n", search);
getch();
}

Q. Explain Binary Search with an

example Binary Search Algorithm

Binary search algorithm finds given element in a list of elements with O(log n) time complexity where
n is total number of elements in the list. The binary search algorithm can be used with only sorted list of
element. That means, binary search can be used only with list of element which are already arranged in an
order. The binary search cannot be used for list of element which are in random order.
1. Read the search element from the user
2. Find the middle element in the sorted list
3. Compare, the search element with the middle element in the sorted list.
4. If both are matching, then display "Given element found!!!" and terminate the function
5. If both are not matching, then check whether the search element is smaller or larger than middle element.
6. If the search element is smaller than middle element, then repeat steps 2, 3, 4 and 5 for the left sub list
of the middle element.
7. If the search element is larger than middle element, then repeat steps 2, 3, 4 and 5 for the right sub list
of the middle element.
8. Repeat the same process until we find the search element in the list or until sublist contains only
one element.
9. If that element also doesn't match with the search element, then display "Element not found in the
list!!!" and terminate the function.
Example 1

Example 2
/*Binary
Search*/
#include<stdio.h>
#include<conio.h>
void main()
{
int i, low, high, mid, n, search,
a[100]; clrscr();
printf("Enter number of elements\n");
scanf("%d",&n);
printf("Enter %d integers\n", n);
for ( i = 0 ; i < n ; i++ )
scanf("%d",&a[i]);
printf("Enter value to find\n");
scanf("%d",&search);
low = 0;
high = n - 1;
mid= (low+high)/2;
while( low <= high )
{
if ( a[mid] < search )
low = mid+ 1;
else if ( a[mid] == search )
{
printf("%d found at location %d.\n", search, mid+1);
break;
}
else
high = mid- 1;
mid= (low + high)/2;
}
if ( low> high )
printf("Not found! %d is not present in the list.\n", search);
getch();
}

Q. Define sorting. Explain bubble sort with an


example. Sorting:
⚫ A Sorting Algorithm is used to rearrange a given array or list elements according to a comparison
operator on the elements. The comparison operator is used to decide the new order of element in the
respective data structure.
⚫ Sorting is to organize a collection of data elements based on the order of a comparable property of
each element.
⚫ The arrangement of data in a preferred order is called sorting in the data structure.
Bubble Sort:
 Bubble sort is also known as exchange sort. Bubble sort is a simplest sorting algorithm.
 In bubble sort algorithm array is traversed from 0 to the length-1 index of the array.
 In this we compare one element to the next element, if the first element is greater than the second
element we simply swap them.
 In other words, bubble sorting algorithm compare two values and put the largest value at largest index.
The algorithm follow the same steps repeatedly until the values of array is sorted.
 In worst-case the complexity of bubble sort is O(n2) and in best-case the complexity of bubble sort is
Ω(n).
Example:
Let the elements of array are –

First Pass
Sorting will start from the initial two elements. Let compare them to check which is greater.
Here, 32 is greater than 13 (32 > 13), so it is already sorted. Now, compare 32 with 26.

Here, 26 is smaller than 36. So, swapping is required. After swapping new array will look like -

Now, compare 32 and 35.

Here, 35 is greater than 32. So, there is no swapping required as they are already sorted.
Now, the comparison will be in between 35 and 10.

Here, 10 is smaller than 35 that are not sorted. So, swapping is required. Now, we reach at the end of the
array. After first pass, the array will be -

Now, move to the second iteration.


Second Pass
The same process will be followed for second iteration.

Here, 10 is smaller than 32. So, swapping is required. After swapping, the array will be -

Now, move to the third iteration.


Third Pass
The same process will be followed for third iteration.
Here, 10 is smaller than 26. So, swapping is required. After swapping, the array will be -

Now, move to the fourth iteration.


Fourth pass
Similarly, after the fourth iteration, the array will be -

Hence, there is no swapping required, so the array is completely sorted.

/*Bubble Sort*/
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,j,temp,n;
clrscr();
printf("\n Enter the size of the array \n");
scanf("%d",&n);
printf("\n Enter the Array Elements : \n");
for(i=0; i<n; i++)
{
scanf("%d",&a[i]);
}
for(i=n-1; i<n; i++)
for(j=0; j<i; j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
printf("Array after sorting is\n");
for(i=0; i<n; i++)
{
printf("%d\t",a[i]);
}
getch();
}

Q. Explain selection sort with an example


SELECTION SORT
⚫ In selection sorting algorithm, find the minimum value in the array then swap it first position.
⚫ In next step leave the first value and find the minimum value within remaining values.
⚫ Then swap it with the value of minimum index position. Sort the remaining values by using same
steps.
⚫ The complexity of selection sort algorithm is in worst-case, average-case, and best case run-time of
Θ(n2), assuming that comparisons can be done in constant time.
Example:
1. Set the first element as minimum.

2. Compare minimum with the second element. If the second element is smaller than minimum, assign
the second element as minimum.

Compare
minimum with the third element. Again, if the third element is smaller, then
assign
minimum to the third element otherwise do nothing. The process goes on until the last
element.

3. After each iteration, minimum is placed in the front of the unsorted list.
4. For each iteration, indexing starts from the first unsorted element. Step 1 to 3 are repeated until
all the elements are placed at their correct positions.
Write a program for Selection sort
/*Selection Sort*/
#include <stdio.h>
#include<conio.h>
void main()
{
int a[100], n, i, j,temp;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d Numbers\n", n);
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
printf("Sorted Array is :\n");
for(i = 0; i < n; i++)
printf("%d\n", a[i]);
getch();
}

Q. Explain Insertion sort with an example.


Insertion Sort:
⚫ Insertion sorting algorithm is similar to bubble sort. But insertion sort is more efficient than bubble
sort because in insertion sort the elements comparisons are less as compare to bubble sort.
⚫ This is implemented by inserting a particular element at the appropriate position.
⚫ In this method the first iteration starts with the comparison of 1st element with 0th element.
⚫ In the second iteration, 2nd element is compared with 0th and 1st elements.
⚫ In general, in every iteration the element is compared with all the elements present before it.
⚫ During the comparison if it is found that the element can be inserted at a suitable position then space is
created for it by shifting the other elements one position to the right and insertion the left element at
the suitable position.
Positive feature of insertion sorting:
⚫ It is simple to implement
⚫ It is efficient on (quite) small data values
⚫ It is efficient on data sets which are already nearly sorted.
⚫ The complexity of insertion sorting is O(n) at best case of an already sorted array and O(n2) at worst
case .
Example:

Write a program for Insertion sort


/* Insertion sort */
#include <stdio.h>
#include<conio.h>
void main()
{
int n, a[1000], i, j,temp;
clrscr();
printf("Enter number of elements\n");
scanf("%d", &n);

printf("Enter %d integers\n", n);

for (i = 0; i < n; i++)


scanf("%d", &a[i]);
for(i=1;i<n;i++)
{
j=j-1;
while((j>=0)&&(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1]
a[j+1]=temp;
j=j-1;
}
}

printf("Sorted list in ascending order:\n");

for (i = 0; i <= n - 1; i++) {


printf("%d\n", a[i]);
}

getch();
}

Q. Explain Quick sort with an example.


Quick sort : Quick sort is a divide-and-conquer sorting algorithm in which division is dynamically carried out
(as opposed to static division in Merge sort). The time complexity for the quick sort is o(n log n). Where ‘n’
represents the number of elements.
Divide: Rearrange the elements and split the array into two sub arrays by placing an element in between these
two sub arrays so that each element in the left sub array is less than or equal the middle element and each
element in the right sub array is greater than the middle element.
Conquer: Recursively sort the two sub arrays.
Combine: Since the sub arrays are sorted in place, no work is needed to combing them: the entire array S is
now sorted.
Q. Explain Merge sort with an example.
Merge Sort:
⚫ Merging is the combination of two or more sorted arrays into a single sorted array. Following figure
illustrates the basic, two-way merge operation. In a two-way merge, two sorted sequences are merged
into one.
⚫ The time complexity for merge sort is O(n log n).
Example1:

Example:2

You might also like