DESIGN & ANALYSIS OF ALGORITHMS
USING C++
Practical File
Submitted by
Name : Md Emat Haider
Semester :V
College Roll No : 2 2CSB028
University Roll No : 221920690007
Academic Year : 2024-2025
Submitted to
Dr. Mohd Shahid
Assistant Professor, CSE
Department of Computer Science and Engineering
Mewat Engineering College (Wakf)
Nuh, Mewat-Haryana-122107
www.mecw.ac.in
Index
Sr. No Experiment Date Signature
1 Write a program in C++ to implement binary
search using iterative approach.
2 Write a program in C++ to implement binary
search using recursive approach.
3 Write a program in C++ to implement binary
search using recursive approach.
4 Write a program in C++ to implement Merge
Sort.
5 Write a program in C++ to implement
Selection Sort.
6 Write a program in C++ for implementation
of fractional Knapsack problem using
Greedy Method.
7 Write a program in C++ for 0/1 Knapsack
problem using Dynamic programming.
8 Write a program in C++ to find the shortest
path from a given vertex to other vertices in
a weighted connected graph using Dijkstra’s
algorithm
9 Write a program in C++ to find the minimum
spanning tree of a given directed graph.
10 Write a program to check whether a given
graph is connected or not using DFS
method.
Program No-1
Write a program in C++ to implement binary search using iterative approach
#include <iostream>
using namespace std;
int binarySearch(int[], int, int, int);
int main()
{
int num[10] = {10, 22, 37, 55, 92, 118};
int search_num, loc=-1;
cout<<"Enter the number that you want to search: ";
cin>>search_num;
loc = binarySearch(num, 0, 6, search_num);
if(loc != -1)
{
cout<<search_num<<" found in the array at the location: "<<loc;
}
else
{
cout<<"Element not found";
}
return 0;
}
int binarySearch(int a[], int first, int last, int search_num)
{
int middle;
if(last >= first)
{
middle = (first + last)/2;
//Checking if the element is present at middle loc
if(a[middle] == search_num)
{
return middle+1;
}
//Checking if the search element is present in greater half
else if(a[middle] < search_num)
{
return binarySearch(a,middle+1,last,search_num);
}
//Checking if the search element is present in lower half
else
{
return binarySearch(a,first,middle-1,search_num);
}
}
return -1;
}
Output
Program No-2
Write a program in C++ to implement binary search using recursive approach
#include <iostream>
using namespace std;
int BinarySearch(int arr[], int num, int beg, int end)
{
int mid;
if (beg > end){
cout << "Number is not found";
return 0;
} else {
mid = (beg + end) / 2;
if(arr[mid] == num){
cout << "Number is found at " << mid << " index \n";
return 0;
} else if (num > arr[mid])
{ BinarySearch (arr, num, mid+1,
end);
} else if (num < arr[mid]) {
BinarySearch (arr, num, beg , mid-1);
}
}
}
int main() {
int arr[100], num, i, n, beg, end;
cout <<"Enter the size of an array (Max 100) \n";
cin >> n;
cout <<"Enter the sorted values \n";
for(i=0; i<n; i++) {
cin >> arr[i];
}
cout <<"Enter a value to be search \n";
cin >> num;
beg = 0;
end = n-1;
BinarySearch (arr, num, beg, end);
return 0;
}
Output
Program No-3
Write a program in C++ to implement Quick Sort.
/* C++ Program to implement Quick Sort */
#include<iostream>
using namespace std;
void QUICKSORT(int [],int ,int );
int PARTITION(int [],int,int );
int main()
{
int n;
cout<<"Enter the size of the array"<<endl;
cin>>n;
int a[n];
cout<<"Enter the elements in the array"<<endl;
for(int i=1;i<=n;i++)
{
cin>>a[i];
}
cout<<"sorting using quick sort"<<endl;
int p=1,r=n;
QUICKSORT(a,p,r);
cout<<"sorted form"<<endl;
for(int i=1;i<=n;i++)
{
cout<<"a["<<i<<"]="<<a[i]<<endl;
}
return 0;
}
void QUICKSORT(int a[],int p,int r)
{
int q;
if(p<r)
{
q=PARTITION(a,p,r);
QUICKSORT(a,p,q-1);
QUICKSORT(a,q+1,r);
}
}
int PARTITION(int a[],int p,int r)
{
int temp,temp1;
int x=a[r];
int i=p-1;
for(int j=p;j<=r-1;j++)
{
if(a[j]<=x)
{
i=i+1;
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
temp1=a[i+1];
a[i+1]=a[r];
a[r]=temp1;
return i+1;
}
Output
Program No-4
Write a program in C++ to implement Merge Sort.
#include<iostream>
using namespace std;
void merge_sort(int [],int ,int );
void merge(int [],int,int ,int );
int main()
{
int n;
cout<<"Enter the size of the array"<<endl;
cin>>n;
int a[n];
cout<<"Enter the elements in the array"<<endl;
for(int i=1;i<=n;i++)
{
cin>>a[i];
}
cout<<"sorting using merge sort"<<endl;
int p=1,r=n;
merge_sort(a,p,r);
cout<<"sorted form"<<endl;
for(int i=1;i<=n;i++)
{
cout<<"a["<<i<<"]="<<a[i]<<endl;
}
return 0;
}
void merge_sort(int a[],int p,int r)
{
int q;
if(p<r)
{
q=(p+r)/2;
merge_sort(a,p,q);
merge_sort(a,q+1,r);
merge(a,p,q,r);
}
}
void merge(int a[],int p,int q,int r)
{
cout<<"Entered merge"<<endl;
int n1=q-p+1;
int n2=r-q;
int L[n1+1];
int R[n2+1];
for(int i=1;i<=n1;i++)
{
L[i]=a[p+i-1];
}
for(int j=1;j<=n2;j++)
{
R[j]=a[q+j];
}
L[n1+1]=999;
R[n2+1]=999;
int i=1, j=1;
for(int k=p;k<=r;k++)
{
if(L[i]<=R[j])
{
a[k]=L[i];
i=i+1;
}
else
{
a[k]=R[j];
j=j+1;
}
}
}
Output
Program No-5
Write a program in C++ to implement Selection Sort.
#include<iostream>
using namespace std;
int main()
{
int i,j,n,loc,temp,min,a[30];
cout<<"Enter the number of elements:";
cin>>n;
cout<<"\nEnter the elements\n";
for(i=0;i<n;i++)
{
cin>>a[i];
}
for(i=0;i<n-1;i++)
{
min=a[i];
loc=i;
for(j=i+1;j<n;j++)
{
if(min>a[j])
{
min=a[j];
loc=j;
}
}
temp=a[i];
a[i]=a[loc];
a[loc]=temp;
}
cout<<"\nSorted list is as follows\n";
for(i=0;i<n;i++)
{
cout<<a[i]<<" ";
}
return 0;
}
Output
Program No-6
Write a program in C++ for implementation of fractional Knapsack problem using
Greedy Method
#include<bits/stdc++.h>
using namespace std;
int main(){
float a[50],aa[50];
int n,temp,i,j;
int constraints,u;
double x[20];
float profit=0,s[10];
cout<<"Enter object & constraints "<<endl;
cin>>n>>constraints;
cout<<"Enter profit and weight"<<endl;
for(int i=0; i<n; i++){
cin>>a[i];
cin>>aa[i];
}
for(i=0; i<n;
i++){s[i]=a[i]/aa
[i];
}
for(i=0; i<n-1;
i++){ for(j=i+1; j<n;
j++){
if(s[i]<s[j])
temp=s[j];
s[j]=s[i];
s[i]=temp;
temp=a[j];
a[j]=a[i];
a[i]=temp;
temp=aa[j];
aa[j]=aa[i];
aa[i]=temp;
}
}
u=constraints;
for(i=0; i<n; i++){
x[i]=0;
}
for(i=0; i<n;
i++){if(aa[i]>u){ b
reak;
}
else{
x[i]=1.0;
profit= profit+a[i];
u=u-aa[i];
}
}
if(i<n)
x[i]=u/aa[i];
profit=profit+a[i]*x[i];
cout<<profit<<endl;
return 0;
}
Output
Program No-7
Write a program in C++ for 0/1 Knapsack problem using Dynamic programming
#include <iostream>
#include <climits>
using namespace std;
// Values (stored in array `v`)
// Weights (stored in array `w`)
// Total number of distinct items `n`
// Knapsack capacity `W`
int knapsack(int v[], int w[], int n, int W)
{
// base case: Negative capacity
if (W < 0) {
return INT_MIN;
}
// base case: no items left or capacity becomes 0
if (n < 0 || W == 0) {
return 0;
}
// Case 1. Include current item `v[n]` in the knapsack and recur for
// remaining items `n-1` with decreased capacity `W-w[n]`
int include = v[n] + knapsack(v, w, n - 1, W - w[n]);
// Case 2. Exclude current item `v[n]` from the knapsack and recur for
// remaining items `n-1`
int exclude = knapsack(v, w, n - 1, W);
// return maximum value we get by including or excluding the current item
return max (include, exclude);
}
// 0–1 Knapsack problem
int main()
{
// input: a set of items, each with a weight and a value
int v[] = { 20, 5, 10, 40, 15, 25 };
int w[] = { 1, 2, 3, 8, 7, 4 };
// knapsack capacity
int W = 10;
// total number of items
int n = sizeof(v) / sizeof(v[0]);
cout << "Knapsack value is " << knapsack(v, w, n - 1, W);
return 0;
}
Output
Program No-8
Write a program in C++ to find the shortest path from a given vertex to other vertices
in a weighted connected graph using Dijkstra’s algorithm
#include<iostream>
#include<stdio.h>
using namespace std;
#define INFINITY 9999
#define max 5
void dijkstra(int G[max][max],int n,int startnode);
int main() {
int G[max][max]={{0,1,0,3,10},{1,0,5,0,0},{0,5,0,2,1},{3,0,2,0,6},{10,0,1,6,0}};
int n=5;
int u=0;
dijkstra(G,n,u);
return 0;
}
void dijkstra(int G[max][max],int n,int startnode)
{int cost[max][max],distance[max],pred[max];
int visited[max],count,mindistance,nextnode,i,j;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(G[i][j]==0)
cost[i][j]=INFINITY;
else
cost[i][j]=G[i][j];
for(i=0;i<n;i++) {
distance[i]=cost[startnode][i];
pred[i]=startnode;
visited[i]=0;
}
distance[startnode]=0;
visited[startnode]=1;
count=1;
while(count<n-1) {
mindistance=INFINITY;
for(i=0;i<n;i++)
if(distance[i]<mindistance&&!visited[i])
{mindistance=distance[i];
nextnode=i;
}
visited[nextnode]=1;
for(i=0;i<n;i++)
if(!visited[i])
if(mindistance+cost[nextnode][i]<distance[i]) {
distance[i]=mindistance+cost[nextnode][i];
pred[i]=nextnode;
}
count++;
}
for(i=0;i<n;i++)
if(i!=startnode) {
cout<<"\nDistance of node"<<i<<"="<<distance[i];
cout<<"\nPath="<<i;
j=i;
do {
j=pred[j];
cout<<"<-"<<j;
}while(j!=startnode);
}
}
Output
Program No-9
Write a program in C++ to find the minimum spanning tree of a given directed graph
#include<iostream>
using namespace std;
// Number of vertices in the graph
const int V=6;
// Function to find the vertex with minimum key value
int min_Key(int key[], bool visited[])
{
int min = 999, min_index; // 999 represents an Infinite value
for (int v = 0; v < V; v++) {
if (visited[v] == false && key[v] < min) {
// vertex should not be visited
min = key[v];
min_index = v;
}
}
return min_index;
}
// Function to print the final MST stored in parent[]
int print_MST(int parent[], int cost[V][V])
{
int minCost=0;
cout<<"Edge \tWeight\n";
for (int i = 1; i< V; i++) {
cout<<parent[i]<<" - "<<i<<" \t"<<cost[i][parent[i]]<<" \n";
minCost+=cost[i][parent[i]];
}
cout<<"Total cost is"<<minCost;
}
// Function to find the MST using adjacency cost matrix representation
void find_MST(int cost[V][V])
{
int parent[V], key[V];
bool visited[V];
// Initialize all the arrays
for (int i = 0; i< V; i++) {
key[i] = 999; // 99 represents an Infinite value
visited[i] = false;
parent[i]=-1;
}
key[0] = 0; // Include first vertex in MST by setting its key vaue to 0. parent[0]
= -1; // First node is always root of MST
// The MST will have maximum V-1 vertices
for (int x = 0; x < V - 1; x++)
{
// Finding the minimum key vertex from the
//set of vertices not yet included in MST
int u = min_Key(key, visited);
visited[u] = true; // Add the minimum key vertex to the MST
// Update key and parent arrays
for (int v = 0; v < V; v++)
{
// cost[u][v] is non zero only for adjacent vertices of u
// visited[v] is false for vertices not yet included in MST
// key[] gets updated only if cost[u][v] is smaller than key[v]
if (cost[u][v]!=0 && visited[v] == false && cost[u][v] < key[v])
{
parent[v] = u; key[v]
= cost[u][v];
}
}
}
// print the final MST
print_MST(parent, cost);
}
// main function
int main()
{
int cost[V][V];
cout<<"Enter the vertices for a graph with 6 vetices";
for (int i=0;i<V;i++)
{
for(int j=0;j<V;j++)
{
cin>>cost[i][j];
}
}
find_MST(cost);
return 0;
}
Output
Program No-10
Write a program to check whether a given graph is connected or not using DFS method
#include<stdio.h>
#include<conio.h>
int a[20][20],reach[20],n;
void dfs(int v)
{
int i;
reach[v]=1;
for(i=1;i<=n;i++)
if(a[v][i] && !reach[i])
{
printf("\n %d->%d",v,i);
dfs(i);
}
}
void main()
{
int i,j,count=0;
clrscr();
printf("\n Enter number of vertices:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
reach[i]=0;
for(j=1;j<=n;j++)
a[i][j]=0;
}
printf("\n Enter the adjacency matrix:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
dfs(1);
printf("\n");
for(i=1;i<=n;i++)
{
if(reach[i])
count++;
}
if(count==n)
printf("\n Graph is connected");
else
printf("\n Graph is not connected");
getch();
}
Output