Daa Lab Manual
Daa Lab Manual
Daa Lab Manual
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)
Algorithm : Partition(A,p,r)
XA[p]
Ip-1
Jr+1
While true do
Repeat jj-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)
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
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.
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
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:
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;
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);
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;
Greedy Method:
At every step, we can make a choice that looks best at the moment, and we get the optimal
solution of the complete 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.
Output:
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>
int main(void) {
//variables
int i, j;
//temp
Job temp;
//number of jobs
int n = 5;
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;
Cout<<"dmax\n"<<dmax;
//required jobs
Cout<<"\nRequired Jobs: ";
for(i = 1; i <= dmax; i++) {
cout<<jobs[timeslot[i]].id;
//required profit
maxprofit = 0;
for(i = 1; i <= dmax; i++) {
maxprofit += jobs[timeslot[i]].profit;
}
Cout<<”\nMax Profit: %d\n"<< maxprofit;
}
Output
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;
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)
//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)
ds←0;
Decrease(Q,s ds)
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
{
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>
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++)
min=dist[w],u=w;
flag[u]=1;
count++;
for(w=1;w<=n;w++)
dist[w]=dist[u]+cost[u][w];
void main()
int n,v,i,j,cost[10][10],dist[10];
clrscr();
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
cost[i][j]=infinity;
scanf("%d",&v);
dij(n,v,cost,dist);
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:
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.
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)
//Output: Graph G with its vertices marked with consecutive integers in the order they
count ←0
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
count ← count + 1
mark v with count and initialize queue with v while queue is not empty do
{
if w is marked with 0
{ count ← count + 1 mark w with count add w to the end 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++)
q[++r]=i;
if(f<=r)
visited[q[f]]=1;
bfs(q[f++]);
void main()
int v;
clrscr();
scanf("%d",&n);
for(i=1;i<=n;i++)
{
q[i]=0;
visited[i]=0;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
scanf("%d",&v); bfs(v);
for(i=1;i<=n;i++)
if(visited[i])
printf("%d\t",i);
getch();
}
22. Implement depth first search algorithm
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)
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 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);
Output:
Aim:
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:
Output: