0% found this document useful (0 votes)
31 views35 pages

EDITED-DAA file.

Uploaded by

ashishnandal0711
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views35 pages

EDITED-DAA file.

Uploaded by

ashishnandal0711
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 35

VAISH COLLEGE OF ENGINEERING

DESIGN AND ANALYSIS OF ALGORITHM


PRACTICAL FILE

SUBMITTED TO: SUBMITTED BY:


Ms. Vishali Name:- Liza
AP, CSE Roll no:- 21/CSE/142
VCE, ROHTAK

INDEX
Sr. Program Sign
no.
1. Write a Program for iterative Binary Search and
Recursive Binary Search.
2. Write a Program to Sort elements using Quick
Sort and determine the time complexity.

3. Write a Program to Sort elements using


Merge Sort and determine the time
complexity.

4. Write a Program to Sort elements using


Selection Sort and determine the time
complexity.

5. Write a program on Fractional Knapsack


problem using Greedy Method

6. 0/1 Knapsack Problem using Dynamic


Programming

7. Write a program to find the shortest path from


a given vertex to other vertex in a weighted
connected graph using Dijkstra’s algorithm.

8. Write a program to find the Minimum Cost


Spanning Tree (MST) of a given undirected
graph using Kruskal’s algorithm and Prims Algo.
9. Write a program to implement N-Queens
problem using backtracking.

10 Write a program to implement the Travelling


Salesman Problem (TSP).
Experiment - 1
Aim:- Write a Program for Iterative Binary Search and Recursive
Binary Search.

● Program for Iterative Binary Search.

#include <iostream>

using namespace std;


int binarySearch(int array[], int x, int low, int high) {
while (low <= high) {
int mid = low + (high - low) / 2;
if (array[mid] == x) {
return mid;
}
else if (array[mid] < x){
low = mid + 1;
}
else{
high = mid - 1;
}
}
return -1;

}
int main() {
int array[] = {3, 4, 5, 6, 7, 8, 9};
int x = 4;
int n = sizeof(array) / sizeof(array[0]);
int result = binarySearch(array, x, 0, n - 1);
if (result == -1) {
cout<<"Not Found";
}
else{
cout<<"Element is found at index"<<result;
}

Output:-

● Program for Recursive Binary Search


#include <iostream>

using namespace std;


int binarySearch(int array[], int x, int low, int high) {
if (high >= low) {
int mid = low + (high - low) / 2;
if (array[mid] == x){
return mid;
}
if (array[mid] > x) {
return binarySearch(array, x, low, mid - 1);
}
return binarySearch(array, x, mid + 1, high);
}
return -1;

}
int main() {
int array[] = {3, 4, 5, 6, 7, 8, 9};
int x = 7;
int n = sizeof(array) / sizeof(array[0]);
int result = binarySearch(array, x, 0, n - 1);
if (result == -1) {
cout<<"Not found";
}
else {
cout<<"Element is found at index"<<result;
}

}
Output:-
Experiment - 2
Aim:- Write a Program to Sort elements using Quick Sort and
determine the time complexity.
#include <bits/stdc++.h>
using namespace std;
void swap(int* a, int* b){
int t = *a;
*a = *b;
*b = t;
}
int partition (int arr[], int low, int high){
int pivot = arr[high];
int i = (low - 1);
for (int j = low; j <= high - 1; j++){
if (arr[j] < pivot){
i++; //
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
void quickSort(int arr[], int low, int high){
if (low < high){
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);

}
}
void printArray(int arr[], int size) {
int i;
for (i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int main() {
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);
cout<<"Before Sorted array --> ";
for(int i=0;i<n;i++){
cout<<arr[i]<<" ";
}
quickSort(arr, 0, n - 1);
cout<<endl;
cout << "After Sorted array--> ";
printArray(arr, n);
return 0;

Time Determine:- Above solution is implemented in Worst Case.


Worst Case:- T(n) = T(0) + T(n-1) + (n)
which is equivalent to
T(n) = T(n-1) + (n)
The solution of above recurrence is (n^2).
Output:-

Experiment -3
Aim:- Write a Program to Sort a Given set of elements using the
Merge Sort and determine the time required to sort the elements
// Merge sort in C++
#include <iostream>
using namespace std;
void merge(int arr[], int p, int q, int r) {
int n1 = q - p + 1;
int n2 = r - q;
int L[n1], M[n2];
for (int i = 0; i < n1; i++){
L[i] = arr[p + i];
}
for (int j = 0; j < n2; j++) {
M[j] = arr[q + 1 + j];
}
int i, j, k;
i = 0;
j = 0;
k = p;
while (i < n1 && j < n2) {
if (L[i] <= M[j]) {
arr[k] = L[i];
i++;
}
else {
arr[k] = M[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = M[j];
j++;
k++;
}
}
void mergeSort(int arr[], int l, int r) {
if (l < r) {
int m = l + (r - l) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);

}
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int main() {
int arr[] = {6, 5, 12, 10, 9, 1};
int size = sizeof(arr) / sizeof(arr[0]);
cout<<"Before Sorted Array --> ";
for(int i=0;i<size;i++){
cout<<arr[i]<<" ";
}
cout<<endl;
mergeSort(arr, 0, size - 1);
cout << "After Sorted array --> ";
printArray(arr, size);
return 0;
}

Time Determine:- Time complexity of Merge Sort is θ(nLogn) in all 3 cases (worst,
average and best) as merge sort always divides the array into two halves and takes
linear time to merge two halves.
Best Case Complexity: O(n*log n)
Worst Case Complexity: O(n*log n)
Average Case Complexity: O(n*log n)

OUTPUT:

Experiment - 4
Aim:- Write a Program to Sort a Given set of elements using the
Selection Sort and determine the time required to sort the
elements.
#include <iostream>
using namespace std;
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void printArray(int array[], int size) {
for (int i = 0; i < size; i++) {
cout << array[i] << " ";
}
cout << endl;
}
void selectionSort(int array[], int size) {
for (int step = 0; step < size - 1; step++) {
int min_idx = step;
for (int i = step + 1; i < size; i++) {
if (array[i] < array[min_idx])
min_idx = i;
}
swap(&array[min_idx], &array[step]);
}
}
int main() {
int data[] = {20, 12, 10, 15, 2};
int size = sizeof(data) / sizeof(data[0]);
cout<<"Before Sorted Array --> ";
for(int i=0;i<size;i++){
cout<<data[i]<<" ";
}
cout<<endl;
selectionSort(data, size);
cout << "After Sorted Array --> ";
printArray(data, size);
}

Time Complexity: O(n2) as there are two nested loops.

Output:-

Experiment - 5
Aim:- Write a program for implementation of Fractional Knapsack
problem using Greedy Method
#include <bits/stdc++.h>
using namespace std;
struct Item {
int value, weight;

Item(int value, int weight)

: value(value), weight(weight)

};
bool cmp(struct Item a, struct Item b)
{
double r1 = (double)a.value / a.weight;

double r2 = (double)b.value / b.weight;

return r1 > r2;

}
double fractionalKnapsack(struct Item arr[],int N, int size)
{
sort(arr, arr + size, cmp);

int curWeight = 0;

double finalvalue = 0.0;

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

if (curWeight + arr[i].weight <= N) {

curWeight += arr[i].weight;

finalvalue += arr[i].value;

else {

int remain = N - curWeight;


finalvalue += arr[i].value*((double)remain/ arr[i].weight);

break;
}

return finalvalue;

}
int main()
{
int N = 60;

Item arr[] = { { 100, 10 },{ 280, 40 },{ 120, 20 },{ 120, 24 } };

int size = sizeof(arr) / sizeof(arr[0]);

cout << "Maximum profit earned = "

<< fractionalKnapsack(arr, N, size);

return 0;

Output:-
Time Complexity: O(N*log2N)

Experiment -6
Aim:- 0/1 Knapsack Problem using Dynamic Programming.

#include <bits/stdc++.h>
using namespace std;

int max(int a, int b) { return (a > b) ? a : b; }


int knapSack(int W, int wt[], int val[], int n)
{
if (n == 0 || W == 0)

return 0;

if (wt[n - 1] > W)

return knapSack(W, wt, val, n - 1);

else

return max(

val[n - 1]+ knapSack(W - wt[n - 1],

wt, val, n - 1),knapSack(W, wt, val, n - 1));

int main()
{
int val[] = { 60, 100, 120 };

int wt[] = { 10, 20, 30 };

int W = 50;

int n = sizeof(val) / sizeof(val[0]);

cout <<"Max Profit is = "<< knapSack(W, wt, val, n);

return 0;

}
Output:-

Time Complexity: O(2n).

Experiment - 7
Aim:- Write a program to find the shortest path from a given vertex
to other vertex in a weighted connected graph using Dijkstra’s
algorithm.

#include <iostream>
using namespace std;
#include <limits.h>
#define V 9
int minDistance(int dist[], bool sptSet[])
{
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
if (sptSet[v] == false && dist[v] <= min)
min = dist[v], min_index = v;

return min_index;
}
void printSolution(int dist[])
{
cout <<"Vertex \t Distance from Source" << endl;
for (int i = 0; i < V; i++)
cout << i << " \t\t"<<dist[i]<< endl;
}
void dijkstra(int graph[V][V], int src)
{
int dist[V];
bool sptSet[V];
for (int i = 0; i < V; i++)
dist[i] = INT_MAX, sptSet[i] = false;
dist[src] = 0;
for (int count = 0; count < V - 1; count++) {
int u = minDistance(dist, sptSet);
sptSet[u] = true;
for (int v = 0; v < V; v++)
if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX
&& dist[u] + graph[u][v] < dist[v])
dist[v] = dist[u] + graph[u][v];
}
printSolution(dist);
}
int main()
{
int graph[V][V] = { { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
{ 4, 0, 8, 0, 0, 0, 0, 11, 0 },
{ 0, 8, 0, 7, 0, 4, 0, 0, 2 },
{ 0, 0, 7, 0, 9, 14, 0, 0, 0 },
{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },
{ 0, 0, 4, 14, 10, 0, 2, 0, 0 },
{ 0, 0, 0, 0, 0, 2, 0, 1, 6 },
{ 8, 11, 0, 0, 0, 0, 1, 0, 7 },
{ 0, 0, 2, 0, 0, 0, 6, 7, 0 } };

dijkstra(graph, 0);
return 0;
}

Output:-
Experiment – 8
Aim:- Write a program to find the Minimum Cost Spanning Tree
(MST) of a given undirected graph using Kruskal’s algorithm and
Prims Algorithm.

● Program to find MST using Kruskals Algorithm.


#include<bits/stdc++.h>
using namespace std;
typedef pair<int, int> iPair;
struct Graph
{
int V, E;

vector< pair<int, iPair> > edges;

Graph(int V, int E)

this->V = V;

this->E = E;

void addEdge(int u, int v, int w)

edges.push_back({w, {u, v}});

int kruskalMST();

};
struct DisjointSets
{
int *parent, *rnk;

int n;

DisjointSets(int n)

{
this->n = n;

parent = new int[n+1];

rnk = new int[n+1];

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

rnk[i] = 0;

parent[i] = i;

int find(int u)

if (u != parent[u])

parent[u] = find(parent[u]);

return parent[u];

void merge(int x, int y)

x = find(x), y = find(y);
if (rnk[x] > rnk[y])

parent[y] = x;

else

parent[x] = y;

if (rnk[x] == rnk[y])

rnk[y]++;

};
int Graph::kruskalMST()
{
int mst_wt = 0;

sort(edges.begin(), edges.end());

DisjointSets ds(V);

vector< pair<int, iPair> >::iterator it;

for (it=edges.begin(); it!=edges.end(); it++)

int u = it->second.first;

int v = it->second.second;

int set_u = ds.find(u);

int set_v = ds.find(v);

if (set_u != set_v)

cout << u << " - " << v << endl;

mst_wt += it->first;

ds.merge(set_u, set_v);

return mst_wt;
}
int main()
{
int V = 9, E = 14;

Graph g(V, E);

g.addEdge(0, 1, 4);

g.addEdge(0, 7, 8);

g.addEdge(1, 2, 8);

g.addEdge(1, 7, 11);

g.addEdge(2, 3, 7);

g.addEdge(2, 8, 2);
g.addEdge(2, 5, 4);

g.addEdge(3, 4, 9);

g.addEdge(3, 5, 14);

g.addEdge(4, 5, 10);

g.addEdge(5, 6, 2);

g.addEdge(6, 7, 1);

g.addEdge(6, 8, 6);

g.addEdge(7, 8, 7);

cout << "Edges of MST are \n";

int mst_wt = g.kruskalMST();

cout << "\nWeight of MST is " << mst_wt;

return 0;

Output:-
● Program to find MST using Prims Algorithm.

#include<iostream>
using namespace std;
const int V=6;
int min_Key(int key[], bool visited[])
{
int min = 999, min_index;
for (int v = 0; v < V; v++) {
if (visited[v] == false && key[v] < min) {
min = key[v];
min_index = v;

}
}
return min_index;
}
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<<endl; cout<<"Total cost is "<<minCost;
}
void find_MST(int cost[V][V])
{
int parent[V], key[V];
bool visited[V];
for (int i = 0; i< V; i++) {
key[i] = 999;
visited[i] = false;
parent[i]=-1;
}
key[0] = 0;
parent[0] = -1;
for (int x = 0; x < V - 1; x++)
{
int u = min_Key(key, visited);
visited[u] = true;
for (int v = 0; v < V; v++)
{
if (cost[u][v]!=0 && visited[v] == false && cost[u][v] < key[v])
{
parent[v] = u;
key[v] = cost[u][v];
}
}
} print_MST(parent, cost);
}
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]; }

}
cout<<endl;
find_MST(cost);
return 0;
}

Output:-
Experiment - 9
Aim:- Write a program to implement N-Queens problem using
backtracking.
#include<iostream>
using namespace std;
int grid[10][10];
void print(int n) {
for (int i = 0;i <= n-1; i++) {
for (int j = 0;j <= n-1; j++) {
cout <<grid[i][j]<< " ";
}
cout<<endl;
}
cout<<endl;
cout<<endl;
}
bool isSafe(int col, int row, int n) {
for (int i = 0; i < row; i++) {
if (grid[i][col]) {
return false;
}
}
for (int i = row,j = col;i >= 0 && j >= 0; i--,j--) {
if (grid[i][j]) {
return false;
}
}
for (int i = row, j = col; i >= 0 && j < n; j++, i--) {
if (grid[i][j]) {
return false;
} } return true;
}
bool solve (int n, int row) {
if (n == row) {
cout<<"The 1 values indicate placements of queens"<<endl;
print(n);
return true;
}
bool res = false;
for (int i = 0;i <=n-1;i++) {
if (isSafe(i, row, n)) {
grid[row][i] = 1;
res = solve(n, row+1) || res;
grid[row][i] = 0;
} } return res;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
cout<<"Enter the number of queen"<<endl;
cin >> n;
for (int i = 0;i < n;i++) {
for (int j = 0;j < n;j++) {
grid[i][j] = 0;
} }
bool res = solve(n, 0);
if(res == false) {
cout << -1 << endl;
} else {
cout << endl;
}
return 0;
}

Output:-
Experiment - 10
Aim:- Write a program to implement the Travelling Salesman
Problem (TSP).

#include <bits/stdc++.h>
using namespace std;
#define V 4
int travllingSalesmanProblem(int graph[][V], int s)
{
vector<int> vertex;
for (int i = 0; i < V; i++)
if (i != s)
vertex.push_back(i);
int min_path = INT_MAX;
do {
int current_pathweight = 0;
int k = s;
for (int i = 0; i < vertex.size(); i++) {
current_pathweight += graph[k][vertex[i]];
k = vertex[i];
}
current_pathweight += graph[k][s];
min_path = min(min_path, current_pathweight);

} while (
next_permutation(vertex.begin(), vertex.end()));

return min_path;
}

int main()
{
int graph[][V] = { { 0, 10, 15, 20 },
{ 10, 0, 35, 25 },
{ 15, 35, 0, 30 },
{ 20, 25, 30, 0 } };
int s = 0;
cout <<"minimum weight = "<<travllingSalesmanProblem(graph, s) <<
endl;
return 0;
}

Output:-

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy