You are on page 1of 37

Sorting Algorithms:

1. To analyze time complexity of Insertion Sort.

Insertion sort:

We pick an element and then insert it at the appropriate position in ascending or descending
order.
1. In pass1, element A[1] is inserted either before or after a[0] so that A[0] and A[1] are sorted.
2. In pass2, element A[2] is inserted either before A[0] or between A[0] and A[1] or after A[1] so
that A[0],A[1] and A[2] are sorted .
3. This process continues until n-1 times.

Algorithm:

Insertion-Sort(A)
Begin
For k=1 to n-1 by 1 do
Set temp=A[k];
Set j=k-1
While temp<a[j] && j>=0 do
Set A[j+1]=A[j]
Set j=j-1
End while
Set A[j+1]=temp
End for
End

Analysis:
Run time of this algorithm is very much dependent on the give input
For N element array
i. In 1st Pass we have 1 comparison
ii. In 2nd pass we have 2 comparisons
iii. Similarly , in Kth pass we have K-1 comparisons and the last pass requires n-1
comparisons.
Total comparisons are
F(n)= 1+2+3+…………………+(n-2)+(n-1)
= n(n-1)/2
=n2-n/2
=O(n2)
2. To analyze time complexity of Quick Sort.

Quick Sort:

It finds the element called Pivot, which divides the array into two parts
The given array A[p……r] into two non-empty sub array A[p…q] and A[q+1….r].
Such that every key in A[p…q] is less than or equal to every key in A[q+1…r].
Then the two sub-arrays are sorted by recursive calls to Quick sort .

Algorithm:

Quick –Sort(A,q,r)
If p<r then
qPartition(A,p,r)
Quick-Sort (A,p,r)
Quick-Sort(A,q+1,r)

We follow three steps:


1. Find Pivot.
2. Quick sort the left sub-array.
3. Quick sort the right sub-array.

Algorithm : Partition(A,p,r)
XA[p]
Ip-1
Jr+1
While true do
Repeat jj-1
Until A[j] <= x
Repeat i u+1
Until A[i]>=x
If i<j then
Exchange A[i]A[j]
Else
Return j

Analysis: ( Worst-case)

1. The original call takes n time for some constant cn.


2. 1 elements takes c(n-1) time.
3. 2 elements takes c(n-2) time.
4. This process goes until finish.
Cn+c(n-1)+c(n-2)+…………….+2c = n+(n(n-1)/2)-1
- = 2n+n2++n-2/2
=n2+3n-2/2
=O(n2) time
Analysis: Best case

1. The n elements take constant cn time.


2. The each partition take n/2 time.
<=2-cn/2 =cn
3. <=4-cn/4 = cn
4. <= 8-cn/8 =cn
5. So using big-O notaion, we get the same result as for merge sort O(n log n) time.
3. To analyze the time complexity of Merge Sort.

Merge sort:
We take an array and divide into into two parts, keep dividing from the middle till we
get only one element in each sub-array.
Then we sort the sub-arrays and merge them back to get the final sorted array.

Algorithm:

Merge-Sort(A[],p,r]
If p<r then
q=(p+r)/2
Merge-sort(A[],p,q)
Merge-sort(A[],q+1,r)
Merge(A[],p,q,r)

Function: Merge(A[],p,q,r)
N1=q-p+1
N2=r-q
Determine leftnums[1…N1+1] and rightnums[1…N2+1] arrays
For i=1 to N1
Leftnums[i]= A[p+i-1]
For j=1 to N2
Rightnums[j]=A[q+j]
Leftnums[N1+1]=a
Rightnums[N2+1]=i
I=1
J=1
For k=p to r
If leftnums[i]> rightnums[i]
A[k]=leftnums[i]
I=i+1
Else
A[k]=rightnums[j]
J=j+1

Analysis:
Let us consider , the running time of Merge-sort as T(n).

T(n) = c if n<=1
2X T(n/2)+dXn otherwise

Where c and d are constants . using this recurrence relation .


T(n) =2iT [n/2i] +i.d.n
I=log n, T(n) =2 log n T[n/2 log n]+log n. d. n
= c.n + d.n.log n
T(n)= O( n log n)
Dynamic Algorithms:

4. To implement largest common sub sequence.

In the Longest-common- subsequence problem , we are given two sub sequences X=(x1,x2...xm)
And Y=(y1,y2………yn) and wish to find out a maximum length common subsequences of X and Y.

Algorithm: To find out the length


LCS – LENGTH(X,Y)
M length[X]
Nlength[Y]
For i1 to m do
C[i,0] 0
For j0 to n do
C[0,j]0
For i1 to m do
For j1 to n do
If xi = y j then
C[i,j] c[i-1,j-1]+1
B[I,j]” ^”
Else if c[i-1,j]>= c[i,j-1] then
C[i,j]  c[i-1,j]
B[i,j]=”^”
Else
C[i,j]c[i,j-1]
B[i,j] “”
Return c and b.

Print –LCS(b,X,i,j)
If i=0 or j=0 then
Return
If b[i,j]=”^” then
Print-LCS(b,X,i-1,j-1)
Print xi
Else if b[i,j]=”^” then
Print-LCS(b,X,i-1,j)
Else
Print-LCS(b,X,i,j-1)

Analysis:
The tables produced by LCS-Length on the sequences X={A,B,C,B,D,A,B} and Y=
b,D,C,A,B,A.
The running time of the procedure is O(mn) since each table entry take O(1) time to compute.
5. IMPLEMENTATION OF Optimal BINARY SEARCH TREE ALGORITHM

Optimal Binary Search tree :


Aim:
In a binary search tree we arrange the key elements in proper order.
First check the condition root>left child
Root<right child
Compare the root and leftchild , we should arrange the elements at left or right
Left child key value should be less than the root value.
Right child key value should be greater than the root value.

Algorithm:
Optimal-binary-search-tree(p,q,n)
E[1…n+1,0…n]
W[1…n+1,0…n]
Root[1…n+1,0…n]
For i=1 to n=1 do
E[i,j-1]:= qi-1
W[i,i-1]: qi-1
For i =1to n do
For i=1 to n-l+1 do
J=i+l-1
E[i,j]:=”
W[i,j]:=w[i,i-1] +pj+qj
For r=i to j do
T:=e[i,r-1]=e[r+1,j]=w[i,j]
If t<e[i,j]
E[i,j]:=t
Root(i,j]:=r
Return e and root.

Analysis:

1. Each for loop takes on at most n values.

2. There are three for loops


3. So The algorithm requires O(n3) time
Divide and conquer:

7.To write a C++ program to perform binary search using the divide and conquer technique.
Algorithm:
Step 1: Start the process.
Step 2: Declare the variables.
Step 3: Enter the list of elements to be searched using the get function.
Step 4: Divide the array list into two halves the lower array list and upper array
List.
Step 5: It works by comparing a search key k with the arrays middle element a[m].
Step 6: If they match the algorithm stops; otherwise the same operation is repeated recursively
for the first half of the array if k < a[m] and the second half if k > a[m].
Step 7: Display the searching results
Step 8: Stop the process.

PROGRAM
#include<iostream.h>
int main()
{
Cout<<”enter the size of an array’;
int size;
cin>>size;
int array[size],key,I;
for(int j=0;j<size;j++)
{
cout<<”enter”<<j<<”element”;
cin>>array[j];
}
For (int a=0;a<size;a++)
{
Cout<<”array[“<<a<<”]=”;
Cout<<array[a];
}
Cout<<”enter key to search in array”
Cin>>key;
First=0;
Last=n-1;
Mid=(first+last)/2;
While(first<=last)
{
If(array[mid]==key)
{
Cout<<key<<”found at location “<<mid+1;
Break;
Else if(array[mid]<key)
{
First=mid+1;
}
Else
{
Last=mid-1;
}
Getch();
}
Output:
Binary Search
Enter the number of elements: 4
Enter the elements:
1
3
7
8
Enter the element to be searched: 8
The element is found at position: 4
8. Implement Merge sort Algorithm.

#include <iostream.h>
// A function to merge the two half into a sorted data.
void Merge(int *a, int low, int high, int mid)
{
// We have low to mid and mid+1 to high already sorted.
int i, j, k, temp[high-low+1];
i = low;
k = 0;
j = mid + 1;

// Merge the two parts into temp[].


while (i <= mid && j <= high)
{
if (a[i] < a[j])
{
temp[k] = a[i];
k++;
i++;
}
else
{
temp[k] = a[j];
k++;
j++;
}
}

// Insert all the remaining values from i to mid into temp[].


while (i <= mid)
{
temp[k] = a[i];
k++;
i++;
}

// Insert all the remaining values from j to high into temp[].


while (j <= high)
{
temp[k] = a[j];
k++;
j++;
}

// Assign sorted data stored in temp[] to a[].


for (i = low; i <= high; i++)
{
a[i] = temp[i-low];
}
}

// A function to split array into two parts.


void MergeSort(int *a, int low, int high)
{
int mid;
if (low < high)
{
mid=(low+high)/2;
// Split the data into two half.
MergeSort(a, low, mid);
MergeSort(a, mid+1, high);

// Merge them to get sorted output.


Merge(a, low, high, mid);
}
}

int main()
{
int n, i;
cout<<"\nEnter the number of data element to be sorted: ";
cin>>n;

int arr[n];
for(i = 0; i < n; i++)
{
cout<<"Enter element "<<i+1<<": ";
cin>>arr[i];
}

MergeSort(arr, 0, n-1);

// Printing the sorted data.


cout<<"\nSorted Data ";
for (i = 0; i < n; i++)
cout<<"->"<<arr[i];

return 0;
}

Output
Enter the number of data element to be sorted :5
Enter element 1:10
Enter element 2:8
Enter element 3:5
Enter element 4:15
Enter element 5:7
Sorted data
5
7
8
10
15
9. Implement Quick sort Algorithm.

#include <iostream.h>
void print(int *a, int n)
{
int i=0;
while(i<n){
cout<<a[i]<<",";
i++;
}
}
void swap(int i,int j, int *a){
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
void quicksort(int *arr, int left, int right){
int min = (left+right)/2;
cout<<"QS:"<<left<<","<<right<<"\n";

int i = left;
int j = right;
int pivot = arr[min];

while(left<j || i<right)
{
while(arr[i]<pivot)
i++;
while(arr[j]>pivot)
j--;

if(i<=j){
swap(i,j,arr);
i++;
j--;
}
else{
if(left<j)
quicksort(arr, left, j);
if(i<right)
quicksort(arr,i,right);
return;
}
}
}

Int main()
{
Int a[6]={10,30,3,6,1,7};
Quicksort(a,n);
Print();
Return 0;
}
Output
The sorted elements are ; 1,3,6,7,10,30
The Greedy Method;

11. Implement activity selection Problem.

Greedy Method:

Greedy method always makes the choice that is optimal solution.

At every step, we can make a choice that looks best at the moment, and we get the optimal
solution of the complete problem.

Activity selection problem:

You are given n activities with their start and finish times. Select the maximum number of activities that
can be performed by a single person, assuming that a person can only work on a single activity at a time.

// C++ program for activity selection problem


// when input activities may not be sorted.
#include <bits/stdc++.h>
using namespace std;

// A job has start time, finish time and profit.


struct Activitiy
{
int start, finish;
};

// A utility function that is used for sorting


// activities according to finish time
bool activityCompare(Activitiy s1, Activitiy s2)
{
return (s1.finish < s2.finish);
}

// Returns count of maximum set of activities that can


// be done by a single person, one at a time.
void printMaxActivities(Activitiy arr[], int n)
{
// Sort jobs according to finish time
sort(arr, arr+n, activityCompare);

cout << "Following activities are selected n";

// The first activity always gets selected


int i = 0;
cout << "(" << arr[i].start << ", " << arr[i].finish << "), ";

// Consider rest of the activities


for (int j = 1; j < n; j++)
{
// If this activity has start time greater than or
// equal to the finish time of previously selected
// activity, then select it
if (arr[j].start >= arr[i].finish)
{
cout << "(" << arr[j].start << ", "
<< arr[j].finish << "), ";
i = j;
}
}
}
// Driver program
int main()
{
Activitiy arr[] = {{5, 9}, {1, 2}, {3, 4}, {0, 6},
{5, 7}, {8, 9}};
int n = sizeof(arr)/sizeof(arr[0]);
printMaxActivities(arr, n);
return 0;
}

Output:

Following activities are selected


(1, 2), (3, 4), (5, 7), (8, 9),

Time Complexity : It takes O(n log n) time if input activities may not be sorted. It takes O(n)
time when it is given that input activities are always sorted.
EXP NO: 12 IMPLEMENTATION OF KNAPSACK PROBLEM
Aim:
To write a C++ program to solve the knapsack problem using greedy method.
Algorithm:
Step1: Start the program.
Step2: Declare the variable.
Step3: Using the get function read the number of items, capacity of the bag,
Weight of the item and value of the items.
Step4: Find the small weight with high value using the find function.
Step5: Find the optimal solution using the function findop ().
Step6: Display the optimal solution for the items.
Step7: Stop the process.
Program:
#include<iostream.h>
#include<conio.h>
int we=0;
class knapsack
{
int max,obj;
float s[100],w[100],p[100],p1[100];
public:
void get();
void calc();
void disc();
};
void knapsack::get()
{
float temp;
cout<<”\nEnter the maximum value of knapsack :”;
cin>>max;
cout<<”\nEnter the number of objects :”;
cin>>obj;
for(i=1;i<=obj;i++)
{
cout<<”\nEnter the value :”;
cin>>w[i];
we+=w[i];
cout<<”\nEnter the profit :”;
cin>>p[i];
p1[i]=p[i]/w[i];
cout<<”\np1=”<<p1[i];
}
for(i=1;i<obj;i++)
for(int j=1;j<=obj;j++)
if(p1[j]<p1[j-1])
{
temp=p1[j];
p1[j]=p1[j+1];
p1[j+1]=temp;
temp=w[j];
w[j]=w[j+1];
w[j+1]=temp;
temp=p[j];
p[j]=p[j+1];
p[j+1]=temp;
}
for(i=1;i<=obj;i++)
cout<<”\n\t\t”<<w[i]<<”\t\t”<<p[i]<<”\t\t ”<<p1[i]<<”\n”;
}
void knapsack::calc()
{
int k=1;as=0;
for(int i=1;i<=obj;i++)
{
for(k=k;k<=w[i]+as;k++)
s[k]=p1[i];
as=k;
we+=w[i];
}
}
void knapsack::disc()
{
float op_w1;
int i;
if(we>=max)
for(i=1;i<=max;i++)
op_w1+=s[i];
out<<”\n Maximum profit= ”<<op_w1;
}
void main()
{
knapsack k;
clrscr();
k.get();
k.calc();
k.disc();
getch();
}

Output:
Enter the maximum value of knapsack: 10
Enter the number of objects: 3
Enter the value 7
Enter the profit 70
P1=10
Enter the value 3
Enter the profit 30
Enter the value 11
Enter the profit 110
P1= 10
7 70 10
3 30 10
11 110 10
Maximum Profit 100
13. Implement Job sequencing with deadlines Algorithm.

This problem consists of n jobs each associated with a deadline and profit and our objective is to earn
maximum profit. We will earn profit only when job is completed on or before deadline. We assume that
each job will take unit time to complete.

#include <iostream.h>

#define MAX 100

typedef struct Job {


char id[5];
int deadline;
int profit;
} Job;

void jobSequencingWithDeadline(Job jobs[], int n);

int minValue(int x, int y) {


if(x < y) return x;
return y;
}

int main(void) {
//variables
int i, j;

//jobs with deadline and profit


Job jobs[5] = {
{"j1", 2, 60},
{"j2", 1, 100},
{"j3", 3, 20},
{"j4", 2, 40},
{"j5", 1, 20},
};

//temp
Job temp;

//number of jobs
int n = 5;

//sort the jobs profit wise in descending order


for(i = 1; i < n; i++) {
for(j = 0; j < n - i; j++) {
if(jobs[j+1].profit > jobs[j].profit) {
temp = jobs[j+1];
jobs[j+1] = jobs[j];
jobs[j] = temp;
}
}
}

Cout<<"Job"<<"Deadline"<< "Profit";
for(i = 0; i < n; i++) {
cout<<jobs[i].id<<jobs[i].deadline<<jobs[i].profit;
}

jobSequencingWithDeadline(jobs, n);

return 0;
}
void jobSequencingWithDeadline(Job jobs[], int n) {
//variables
int i, j, k, maxprofit;

//free time slots


int timeslot[MAX];

//filled time slots


int filledTimeSlot = 0;

//find max deadline value


int dmax = 0;
for(i = 0; i < n; i++) {
if(jobs[i].deadline > dmax) {
dmax = jobs[i].deadline;
}
}

//free time slots initially set to -1 [-1 denotes EMPTY]


for(i = 1; i <= dmax; i++) {
timeslot[i] = -1;
}

Cout<<"dmax\n"<<dmax;

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


k = minValue(dmax, jobs[i - 1].deadline);
while(k >= 1) {
if(timeslot[k] == -1) {
timeslot[k] = i-1;
filledTimeSlot++;
break;
}
k--;
}

//if all time slots are filled then stop


if(filledTimeSlot == dmax) {
break;
}
}

//required jobs
Cout<<"\nRequired Jobs: ";
for(i = 1; i <= dmax; i++) {
cout<<jobs[timeslot[i]].id;

if(i < dmax) {


cout<<" --> ";
}
}

//required profit
maxprofit = 0;
for(i = 1; i <= dmax; i++) {
maxprofit += jobs[timeslot[i]].profit;
}
Cout<<”\nMax Profit: %d\n"<< maxprofit;
}
Output

Job Deadline Profit


j2 1 100
j1 2 60
j4 2 40
j3 3 20
j5 1 20
dmax: 3

Required Jobs: j2 --> j1 --> j3


Max Profit: 180
EXP NO: 14 IMPLEMENTATION OF MINIMUM SPANNING TREE
Aim:
To write a C++ program to find the minimum spanning tree using prim’s algorithm
Algorithm:
Step1: Start the program.
Step2: Declare the variables.
Step3: Using the get function get the number of vertices and enter their weights.
Step4: Using the cal function calculate the minimum spanning tree.
Step5: Display the minimum spanning tree for the given weighted graph.
Step6: End the program
PROGRAM:
#include<iostream.h>
#include<conio.h>
class prim
{
int a,b,u,v,i,j,n,noe;
int vi[10],min,mc,c[10][10];
public:
prim()
{
noe=1;
mc=0;
void read();
void prims(c[][10],int n);
};
void prim::read()
{
cout<<”\n\nEnter the number of vertices :”;
cin>>n;
cout<<\nEnter the adjacency matrix :\n”;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
cin>>c[i][j];
if(c[i][j]==0)
c[i][j]=999;
}
}
prims(c,n);
}
void prim::prims(int c[][10],int n)
{
for(i=2;i<=n;i++)
vi[i]=0;
cout<<”\nEdges in the spanning tree are :\n;
vi[1]=1;
while(noe<1)
{
for(i=1,min=999;i<=1;i++)
for(j=1;j<=n;j++)
if(c[i][j]<min)
if(vi[i]==0)
continue;
else
{
min=c[i][j];
a=u=i;
b=v=j;
}
if((vi[u]==0)||(vi[v]==0))
noe++;
cout<<”\nEdge(”<<a<<”-->”<<b<<”) :”<<min;
mc+=min;vi[b]=1;
}
c[a][b]=c[b][a]=999;
}
cout<<”\n\nMinimum cost spanning tree is :”<<mc;
}
void main()
{
clrscr();
cout<<”\nPrims algorithm\n”;
prim p;
p.read();
getch();
}

Output:
PRIM'S ALGORITHM
Enter the number of vertices: 3
Enter the adjacency matrix:
052
501
010
Enter the spanning tree are:
Edge <1---->3>: 2
Edge<3---->2>: 1
Minimum cost spanning tree is: 3
14. Implement single source shortest paths: Dijkstra’s Algorithm.

Aim;

Single Source Shortest Paths Problem:

1. For a given vertex called the source in a weighted connected graph, find the shortest paths to all
its other vertices.
2. Dijkstra‟s algorithm is the best known algorithm for the single source shortest paths problem.
3. This algorithm is applicable to graphs with nonnegative weights only and finds the shortest
paths to a graph‟s vertices in order of their distance from a given source.
4. It finds the shortest path from the source to a vertex nearest to it, then to a second nearest,
and so on. It is applicable to both undirected and directed graphs

Algorithm : Dijkstra(G,s)

//Dijkstra‟s algorithm for single-source shortest paths

//Input :A weighted connected graph G=(V,E) with nonnegative weights and its vertex s

//Output : The length dv of a shortest path from s to v and its penultimate vertex pv for //every v in V.

Initialise(Q)

// Initialise vertex priority queue to empty for every vertex v in V do

dv←œ; pv←null Insert(Q,v,dv)

//Initialise vertex priority queue in the priority queue

ds←0;

Decrease(Q,s ds)

//Update priority of s with ds Vt←Ø for i←0 to |v|-1 do

u* ← DeleteMin(Q)

//delete the minimum priority element Vt ←Vt U {u*} for every vertex u in V-Vt that is adjacent to u* do
{

if du* + w(u*,u)<du { du←du* + w(u*, u): pu←u* Decrease(Q,u,du) } } } }

Complexity: The Time efficiency for graphs represented by their weight matrix and the priority queue
implemented as an unordered array and for graphs represented by their adjacency lists and the priority
queue implemented as a min-heap, it is O(|E| log |V|).
13. implement minimum –cost spanning trees.

#include<stdio.h>

#include<conio.h>

#define infinity 999

void dij(int n,int v,int cost[10][10],int dist[100])

int i,u,count,w,flag[10],min;

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

flag[i]=0,dist[i]=cost[v][i];

count=2;

while(count<=n)

min=99;

for(w=1;w<=n;w++)

if(dist[w]<min && !flag[w])

min=dist[w],u=w;

flag[u]=1;

count++;

for(w=1;w<=n;w++)

if((dist[u]+cost[u][w]<dist[w]) && !flag[w])

dist[w]=dist[u]+cost[u][w];

void main()

int n,v,i,j,cost[10][10],dist[10];

clrscr();

printf("\n Enter the number of nodes:");

scanf("%d",&n); printf("\n Enter the cost matrix:\n");


for(i=1;i<=n;i++) for(j=1;j<=n;j++)

scanf("%d",&cost[i][j]);

if(cost[i][j]==0)

cost[i][j]=infinity;

printf("\n Enter the source matrix:");

scanf("%d",&v);

dij(n,v,cost,dist);

printf("\n Shortest path:\n");

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

if(i!=v)

printf("%d->%d,cost=%d\n",v,i,dist[i]);

getch();

}
16. Implement single-source shortest paths: Bellman-Ford’s Algorithm.

Aim:

The algorithm cannot solve this problem and cannot give you a definite path. It is theoretically
impossible to find out the shortest path if there exists a negative weight cycle. If you happen to find the
shortest path, then you can go through the negative cycle once more and get a smaller path. You can
keep repeating this step and go through the cycle every time and reduce the total weight of the path to
negative infinity.

Algorithm:

public boolean shortestPath(Vertex source, List<Edge> edges, int vertexCount)


{
source.min = 0;

for (int i = 0; i < vertexCount; i++) {


for (Edge e : edges) {
int edgeWeight = e.weight;
int sourceMin = e.start.min;
int currentMin = e.end.min;
int tempDistance = edgeWeight + sourceMin;
if (tempDistance < currentMin) {
e.end.min = tempDistance;
e.end.previous = e.start;
}
}
}

boolean negativeCycle = false;


for (Edge e : edges) {
int edgeWeight = e.weight;
int sourceMin = e.start.min;
int currentMin = e.end.min;
int tempDistance = edgeWeight + sourceMin;
if (tempDistance < currentMin) {
negativeCycle = true;
break;
}
}

return negativeCycle;
}
Output

Analysis of Algorithm
1. The initialization loop runs |V| times.
2.
o The outer for loop runs |V| – 1 times.
o The inner loop runs |E| times for each iteration of the outer loop.
3. The last loop runs for |E| times.

Step 1 takes O(|V|) time, Step 2 takes O(|V| . |E|) times and Step 3 takes O(|E|) times. Hence the
running time would be dominated by the term O(|V| . |E|).
17 IMPLEMENTATION OF ALL PAIR SHORTEST PATH ALGORITHM

Aim:
To write a C++ program to find the shortest path using Floyd’s algorithm.
Algorithm:
Step1: Start the program.
Step2: Declare the variables.
Step3: Using the get function get the number of vertices and enter their weights.
Step4: Using the cal function calculate the shortest path
Step5: Display the shortest path distance graph.
Step6: End the program.
PROGRAM:
#include<iostream.h>
#include<conio.h>
int a[10][10];
int cost[10][10];
int mini(int,int);
int main()
{
clrscr();
int i,j,k,n,m;
cout<<”\n\nEnter the number of vertices :”;
cin>>n;
cout<<\nEnter the no.of edge :\n”;
cin>>m;
cout<<\nEnter the matrix :\n”;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
cin>>a[i][j];
}
}
for(k=0;k<n;k++)
{
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
a[i][j]=mini(a[i][j],a[i][k]+a[k][j]);
}
}
}
cout<<”\n\nThe all pair shortest path is :\n”;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
cout<<”\n”<<i<<”-->”<<j<<” : ”<<a[i][j];
}
}
cout<<”\n\nThe cost matrix is :\n\n”;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
cout<a[i][j]<<” ”;
}
cout<<”\n”;
}
getch();
return 0;
}
int mini(int a,int b)
{
if(a<b)
return a;
else
return b;
}

OUTPUT
ENTER THE NUMBER OF VERTICES: 3
ENTER THE NUMBER OF EDGES: 5
ENTER THE DISTANCE MATRIX:
0 4 15
28 0 2
3 999 0
THE ALL PAIR SHORTEST PATH OF THE GRAPH
0->0: 0
0->1: 4
0->2: 6
1->0: 5
1->1: 0
1->2: 2
2->0: 3
2->1: 7
2->2: 0
THE COST MATRIX IS:
0 4 6
5 0 2
3 9 8
/*Compute the transitive closure of a given directed graph using Warshall's agorithm.*/

#include<stdio.h>

void warshall(int[10][10],int);
void main()
{
int a[10][10],i,j,n;
clrscr();
cout<<"Enter the number of nodes:";
cin>>n;
cout<<"\nEnter the adjacency matrix:\n";
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
cin>>a[i][j];
cout<<"The adjacency matirx is:\n";
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
Cout<<a[i][j];
}
Cout<<"\n";
}
warshall(a,n);
getch();
}
void warshall(int p[10][10],int n)
{
int i,j,k;
for(k=1;k<=n;k++)
{
for(j=1;j<=n;j++)
{
for(i=1;i<=n;i++)
{
if((p[i][j]==0) && (p[i][k]==1) && (p[k][j]==1))
{
p[i][j]=1;
}
}
}
}
Cout<<"\nThe path matrix is:\n";

for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
Cout<<p[i][j];
}
Cout<<"\n";
}
}
OUTPUT:
21. Print all the nodes reachable from a given starting node in a digraph using BFS method.

Breadth First Search:

BFS explores graph moving across to all the neighbors of last visited vertex traversals i.e., it proceeds in
a concentric manner by visiting all the vertices that are adjacent to a starting vertex, then all unvisited
vertices two edges apart from it and so on, until all the vertices in the same connected component as
the starting vertex are visited. Instead of a stack, BFS uses queue.

Algorithm : BFS(G)

//Implements a breadth-first search traversal of a given graph

//Input: Graph G = (V, E)

//Output: Graph G with its vertices marked with consecutive integers in the order they

//have been visited by the BFS traversal

mark each vertex with 0 as a mark of being “unvisited”

count ←0

for each vertex v in V do

if v is marked with 0

bfs(v)

Algorithm : bfs(v)

//visits all the unvisited vertices connected to vertex v and assigns them the numbers

//in order they are visited via global variable count

count ← count + 1

mark v with count and initialize queue with v while queue is not empty do

a := front of queue for each vertex w adjacent to a do

{
if w is marked with 0

{ count ← count + 1 mark w with count add w to the end of the queue

remove a from the front of the queue

Complexity: BFS has the same efficiency as DFS: it is Θ (V2) for Adjacency matrix representation and Θ
(V+E) for Adjacency linked list representation.

#include<stdio.h>

#include<conio.h>

int a[20][20],q[20],visited[20],n,i,j,f=0,r=-1;

void bfs(int v)

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

if(a[v][i] && !visited[i])

q[++r]=i;

if(f<=r)

visited[q[f]]=1;

bfs(q[f++]);

void main()

int v;

clrscr();

printf("\n Enter the number of vertices:");

scanf("%d",&n);

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

q[i]=0;

visited[i]=0;

printf("\n Enter graph data in matrix form:\n");

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

for(j=1;j<=n;j++)

scanf("%d",&a[i][j]);

printf("\n Enter the starting vertex:");

scanf("%d",&v); bfs(v);

printf("\n The node which are reachable are:\n");

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

if(visited[i])

printf("%d\t",i);

getch();

}
22. Implement depth first search algorithm

Depth First Search:

1. Depth-first search starts visiting vertices of a graph at an arbitrary vertex by marking it as having
been visited.
2. On each iteration, the algorithm proceeds to an unvisited vertex that is adjacent to the one it is
currently in.
3. This process continues until a vertex with no adjacent unvisited vertices is encountered.
4. At a dead end, the algorithm backs up one edge to the vertex it came from and tries to continue
visiting unvisited vertices from there.
5. The algorithm eventually halts after backing up to the starting vertex, with the latter being a
dead end.

Algorithm : DFS(G)

//Implements a depth-first search traversal of a given graph


//Input : Graph G = (V,E)
//Output : Graph G with its vertices marked with consecutive integers in the order they
//have been first encountered by the DFS traversal
{
mark each vertex in V with 0 as a mark of being “unvisited”.
count ← 0
for each vertex v in V do
if v is marked with 0
dfs(v)
}
Algorithm : dfs(v)
//visits recursively all the unvisited vertices connected to vertex v by a path
//and numbers them in the order they are encountered via global variable count
{ count ← count+1
mark v with count for each vertex w in V adjacent to v do
if w is marked with 0
dfs(w)
}

Complexity: For the adjacency matrix representation, the traversal time efficiency is in Θ(|V|2) and for
the adjacency linked list representation, it is in Θ(|V|+|E|), where |V| and |E| are the number of
graph‟s vertices and edges respectively.
/* Check whether a given graph is connected or not using DFS method.*/

#include<stdio.h>

void DFS(int [20][20],int,int [20],int);

void main()
{
int n,a[20][20],i,j,visited[20],source;
clrscr();
cout<<"Enter the number of vertices: ";
cin>>n;
cout<<”\nEnter the adjacency matrix:\n";
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
cin>>a[i][j];
for(i=1;i<=n;i++)
visited[i]=0;
cout<<"\nEnter the source node: ";
cin>>source;
DFS(a,source,visited,n);
for(i=1;i<=n;i++)
{
if(visited[i]==0)
{
Cout<<“\nGraph is not connected";
getch();
exit(0);
}
}
Cout<<"\nGraph is connectd\n";
getch();
}
void DFS(int a[20][20],int u,int visited[20],int n)
{
int v;
visited[u]=1;
for(v=1;v<=n;v++)
{ if(a[u][v]==1 && visited[v]==0)
DFS(a,v,visited,n);
}
}
23. implement Naïve string matching algorithm.

Aim:
#include<iostream.h>
#include<string.h>
void search(char *pat, char *txt)
{
int M = strlen(pat);
int N = strlen(txt);

/* A loop to slide pat[] one by one */


for (int i = 0; i <= N - M; i++)
{
int j;

/* For current index i, check for pattern match */


for (j = 0; j < M; j++)
{
if (txt[i + j] != pat[j])
break;
}
if (j == M) // if pat[0...M-1] = txt[i, i+1, ...i+M-1]
{
Cout<<"Pattern found at index %d \n”<<i;
}
}
}

/* Driver program to test above function */


int main()
{
char *txt = "AABAACAADAABAAABAA";
char *pat = "AABA";
search(pat, txt);
return 0;
}

Output:

Pattern found at index 0


Pattern found at index 9
Pattern found at index 13
24. Implement Rabin-karp string matching algorithm.

Aim:

1. Assume the text string t is of length m and the pattern string p is of


length n •
2. Let si denote the length-n contiguous substring of t beginning at offset
i≥0 – So, for example, s0 is the length-n prefix of t •
3. The main idea is to use a hash function h to map each si to a good-
sized set such as the set of the first k nonnegative integers, for some
suitable k – Initially, we compute h(p) – Whenever we encounter an i
for which h(si) = h(p), we check for a match as in the naive algorithm
– If h(si)6= h(p), we don’t need to check for a match

Algorithm:

Robin-Karp(T,P)
N=T.length
M=P.length
HP=Hash(P)
HT=hash(T[0…M-1])
For s=0 to N-M
If(HP==HT)
If(P[0…M-1]=T[S…S+M-1]
Print “Pattern found with shift” S
If(s<N-M)
HT=hash(T[S+1,….S+M])

Program:

// correctly calculates a mod b even if a < 0


function int_mod(int a, int b)
{
return (a % b + b) % b;
}

function Rabin_Karp(text[], pattern[])


{
// let n be the size of the text, m the size of the
// pattern, B - the base of the numeral system,
// and M - a big enough prime number

if(n < m) return; // no match is possible

// calculate the hash value of the pattern


hp = 0;
for(i = 0; i < m; i++)
hp = int_mod(hp * B + pattern[i], M);

// calculate the hash value of the first segment


// of the text of length m
ht = 0;
for(i = 0; i < m; i++)
ht = int_mod(ht * B + text[i], M);

if(ht == hp) check character by character if the first


segment of the text matches the pattern;

// start the "rolling hash" - for every next character in


// the text calculate the hash value of the new segment
// of length m; E = (Bm-1) modulo M
for(i = m; i < n; i++) {
ht = int_mod(ht - int_mod(text[i - m] * E, M), M);
ht = int_mod(ht * B, M);
ht = int_mod(ht + text[i], M);
if(ht == hp) check character by character if the
current segment of the text matches
the pattern;
}
}
/* Driver program to test above function */
int main()
{
char *txt = "AABAACAADAABAAABAA";
char *pat = "AABA";
Robin-karp(pat, txt);
return 0;
}

Output:

Pattern found at index 0


Pattern found at index 9
Pattern found at index 13

You might also like