Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 68

UNIVERSITY INSTITUTE OF ENGINEERING AND

TECHNOLOGY, PANJAB UNIVERSITY, CHANDIGARH

DESIGN AND ANALYSIS OF ALGORITHMS


PRATICAL FILE

SUBMITTED BY: SUBMITTED TO:


TRISHAN PREET SINGH AMANPREET KAUR
UE218105
IT 3rd year
PRACTICAL - 1

AIM: Details of platform, language, and operating system

a. Operating system - Windows 11

Specifications -
Processor: AMD Ryzen 7 4800HS with Radeon Graphics 2.90GHz
System Type: 64-bit operating system, x64-based processor
RAM: 16.0 GB (15.4 GB usable)
OS Build: 22621.2134

b. Language – C++

C++ is the most used and most popular programming language developed by Bjarne
Stroustrup. C++ is a high-level and object-oriented programming language. This
language allows developers to write clean and efficient code for large applications and
software development, game development, and operating system programming. It is
an expansion of the C programming language to include Object Oriented
Programming(OOPs) and is used to develop programs for computers. This C++
Tutorial will cover all the basic to advanced topics of C++ like C++ basics, C++
functions, C++ classes, OOPs and STL concepts.
Features of C++ :
1. Object-Oriented Programming
2. Machine Independent
3. Simple
4. High-Level Language
5. Popular
6. Case-sensitive
7. Compiler Based
8. Dynamic Memory Allocation
9. Memory Management
10. Multi-threading

c. Platform – VS Code:

Visual Studio Code is a lightweight, yet powerful source code editor developed by
Microsoft. It offers a rich set of features, including smart code completion, built-in
Git integration, debugging support, and a vast library of extensions. Its cross-
platform availability makes it a go-to choose for developers working on various
operating systems. With its fast performance and highly customizable interface, VS
Code has garnered a large and active community of users, making it one of the most
popular code editors for a wide range of programming languages and development
tasks.

Features :
1. Lightweight and Fast
2. Language Support
3. Integrated Development Environment (IDE) Features:
4. Integrated Terminal
PRACTICAL – 2

AIM: Write a program to sort a given set of elements and determine the time required
to sort the elements. Repeat the exp for different values of n, the number of elements in
list to be sorted and plot a graph of the time v/s n elements.

2.1 BUBBLE SORT

Libraries Used: -

1) Random No Generator:
Library used for generating random number:
< cstdlib>,<time.h>
Function Invoked:
rand()

2) Time of Execution:
Library used for checking time of execution for each run:
<chrono>
Function Invoked:
chrono::high_resolution_clock::now();

3) Dynamic Array:
Library used for checking time of execution for each run:
<vector>

4) Plotting the outcome:


We used Excel to store the no. of inputs and time taken, and a graph is plot based on this.
Written Code: -

#include <iostream>

#include <chrono>

#include <vector>

using namespace std;

void ascending_sort(int arr[], int n)

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

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

if (arr[j] > arr[j + 1])

swap(arr[j], arr[j + 1]);

void descending_sort(int arr[], int n)

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

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

if (arr[j] < arr[j + 1])

swap(arr[j], arr[j + 1]);

void bubbleSort(int arr[], int n)

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

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

if (arr[j] > arr[j + 1])

swap(arr[j], arr[j + 1]);

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


{

cout << arr[i] << " ";

int main()

chrono::time_point<chrono::system_clock> start, end;

int n;

cout << "Enter the Numbers : ";

cin >> n;

int *arr = new int[n];

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

arr[i] = rand();

// ascending_sort(arr, n);

descending_sort(arr,n);

start = std::chrono::system_clock::now();

cout << "Bubble Sort : ";

bubbleSort(arr, n);
cout << '\n';

end = chrono::system_clock::now();

chrono::duration<double> elapsed_seconds = end - start;

time_t end_time = chrono::system_clock::to_time_t(end);

cout << "finished computation at " << std::ctime(&end_time) << "Elapsed time: " <<
elapsed_seconds.count() << "s\n";

delete[] arr;

return 0;

OUTPUT: -

GRAPH: -
Bubble Sort Time Graph

2.75
2.25
1.75
TIme

1.25
0.75
0.25
1 10 100 500 1000 2000 5000 10000
Best Case 0.001 0.003121 0.018973 0.094824 0.210166 0.40591 1.01975 2.13994
(sec)
Average Case 0.001 0.002996 0.019299 0.096289 0.193636 0.396648 1.07751 2.2574
(sec)
Worst Case 0.001 0.002504 0.020566 0.092271 0.197371 0.406942 1.15113 2.43272
(sec)

PRACTICAL – 3

3.1 LINEAR SEARCH

Libraries Used: -

1) Random No Generator:
Library used for generating random number:
< cstdlib>,<time.h>
Function Invoked:
rand()

2) Time of Execution:
Library used for checking time of execution for each run:
<chrono>
Function Invoked:
chrono::high_resolution_clock::now();
3) Dynamic Array:
Library used for checking time of execution for each run:
<vector>

4) Plotting the outcome:


We used Excel to store the no. of inputs and time taken, and a graph is plot based on this.

Written Code: -
#include <iostream>

#include <vector>

#include <chrono>

#include <cstdlib>

using namespace std;

auto linear_search(vector<int> arr, int n, int key)

auto start = std::chrono::high_resolution_clock::now();

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

if (arr[i] == key)

break;
}

auto end = std::chrono::high_resolution_clock::now();

auto time = end - start;

return time;

int main()

int n;

cout << "Enter the value of n: ";

cin >> n;

vector<int> arr;

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

arr.push_back(rand());

int best_key = arr[0]; // Best case: the key is found in the first element

int worst_key = rand(); // Worst case: the key is not in the array, so it's a random value

int avg_key = arr[rand() % n]; // Average case: a random key from the array

auto best_time = linear_search(arr, n, best_key);

cout << "Time taken for best case: " << (best_time.count()) << " microseconds" << endl;
auto worst_time = linear_search(arr, n, worst_key);

cout << "Time taken for worst case: " << (worst_time.count()) << " microseconds" <<
endl;

auto avg_time = linear_search(arr, n, avg_key);

cout << "Time taken for average case: " << (avg_time.count()) << " microseconds" <<
endl;

return 0;

OUTPUT: -

GRAPH: -
Linear SearchTime Graph

65

55

45
TIme

35

25

15

5
1 10 100 500 1000 2000 5000 10000
Best Case (μ sec) 0 0 0 0 0 0 0 NaN
Average Case (μ sec) 0 0 1 3 4 11 30 NaN
Worst Case (μ sec) 0 0 2 6 8 23 59 NaN
3.2 BINARY SEARCH

Libraries Used: -

1) Random No Generator:
Library used for generating random number:
< cstdlib>,<time.h>
Function Invoked:
rand()

2) Time of Execution:
Library used for checking time of execution for each run:
<chrono>
Function Invoked:
chrono::high_resolution_clock::now();

3) Dynamic Array:
Library used for checking time of execution for each run:
<vector>

4) Plotting the outcome:


We used Excel to store the no. of inputs and time taken, and a graph is plot based on this.
Written Code: -
#include <iostream>
#include<bits/stdc++.h>
#include<time.h>
#include<cstdlib>
#include <vector>
#include <chrono>
using namespace std;

auto average_binary_search(vector<int> arr, int n)


{
int key = arr[0];
sort(arr.begin(), arr.end());
auto start = std::chrono::high_resolution_clock::now();
int left = 0;
int right = n - 1;
while (left <= right)
{
int mid = (left + right) / 2;
if (arr[mid] == key)
{
break;
}
else if (arr[mid] > key)
{
right = mid - 1;
}
else
{
left = mid + 1;
}
}
auto end = std::chrono::high_resolution_clock::now();
auto time = end - start;
return time;
}
auto best_binary_search(vector<int> arr, int n)
{

sort(arr.begin(), arr.end());
auto start = std::chrono::high_resolution_clock::now();
int left = 0;
int right = n - 1;
int key = arr[(left + right) / 2];
while (left <= right)
{
int mid = (left + right) / 2;
if (arr[mid] == key)
{
break;
}
else if (arr[mid] > key)
{
right = mid - 1;
}
else
{
left = mid + 1;
}
}
auto end = std::chrono::high_resolution_clock::now();
auto time = end - start;
return time;
}
auto worst_binary_search(vector<int> arr, int n)
{
int key = arr[n - 1];
sort(arr.begin(), arr.end());
auto start = std::chrono::high_resolution_clock::now();
int left = 0;
int right = n - 1;
while (left <= right)
{
int mid = (left + right) / 2;
if (arr[mid] == key)
{
break;
}
else if (arr[mid] > key)
{
right = mid - 1;
}
else
{
left = mid + 1;
}
}
auto end = std::chrono::high_resolution_clock::now();
auto time = end - start;
return time;
}
int main()
{
int T;
cout << "Enter the number of values of n:";
cin >> T;
for (int i = 0; i < T; i++)
{
int n;
cout << "Enter the value of n:";
cin >> n;
vector<int> arr;
for (int i = 0; i < n; i++)
{
arr.push_back(rand());
}
auto best_time = best_binary_search(arr, n);
cout << "Time taken for best case=" << (best_time / std::chrono::nanoseconds(1)) <<
"nanoseconds" << endl;
auto average_time = average_binary_search(arr, n);
cout << "Time taken for average case=" << (average_time /
std::chrono::nanoseconds(1)) << "microseconds" << endl;
auto worst_time = worst_binary_search(arr, n);
cout << "Time taken for average case=" << (worst_time / std::chrono::nanoseconds(1))
<< "microseconds" << endl;
}
return 0;
}

OUTPUT: -

GRAPH: -

Binary Search Time Graph


1900
1700
1500
1300
TIme

1100
900
700
500
300
100
10 100 500 1000 5000 10000
Best Case (μ sec) 1 8 57 131 772 1559
Average Case (μ sec) 1 11 54 138 742 1628
Worst Case (μ sec) 1 12 55 168 838 1848
3.3 MERGE SORT

Libraries Used: -

1) Random No Generator:
Library used for generating random number:
< cstdlib>,<time.h>
Function Invoked:
rand()

2) Time of Execution:
Library used for checking time of execution for each run:
<chrono>
Function Invoked:
chrono::high_resolution_clock::now();

3) Dynamic Array:
Library used for checking time of execution for each run:
<vector>

4) Plotting the outcome:


We used Excel to store the no. of inputs and time taken, and a graph is plot based on this.
Written Code: -
#include <iostream>
#include <time.h>
#include <cstdlib>
#include <chrono>
#include <vector>

using namespace std;

void merge(vector<int> &arr, int start, int mid, int end)


{

int len1 = mid - start + 1;


int len2 = end - mid;
int *first = new int[len1];
int *second = new int[len2];
int main_arr_index = start;
for (int i = 0; i < len1; i++)
{
first[i] = arr[main_arr_index++];
}
int k = mid + 1;
for (int i = 0; i < len2; i++)
{
second[i] = arr[k++];
}
int index1 = 0;
int index2 = 0;
main_arr_index = start;
while (index1 < len1 && index2 < len2)
{
if (first[index1] < second[index2])
{
arr[main_arr_index++] = first[index1++];
}
else
{
arr[main_arr_index++] = second[index2++];
}
}
while (index1 < len1)
{
arr[main_arr_index++] = first[index1++];
}
while (index2 < len2)
{
arr[main_arr_index++] = second[index2++];
}
delete[] first;
delete[] second;
}
void mergeSort(vector<int> &arr, int start, int end)
{
if (start >= end)
{
return;
}
int mid = (start + end) / 2;
mergeSort(arr, start, mid);
mergeSort(arr, mid + 1, end);
merge(arr, start, mid, end);
}
auto average_merge_sort(vector<int> arr, int n)
{
auto start = std::chrono::high_resolution_clock::now();
mergeSort(arr, 0, n - 1);
auto finish = std::chrono::high_resolution_clock::now();
auto time = finish - start;
return time;
}
auto best_merge_sort(int n)
{
vector<int> arr;
for (int i = 0; i < n; i++)
{
arr.push_back(i);
}
auto start = std::chrono::high_resolution_clock::now();
mergeSort(arr, 0, n - 1);
auto finish = std::chrono::high_resolution_clock::now();
auto time = finish - start;
return time;
}
auto worst_merge_sort(int n)
{
vector<int> arr;
for (int i = n - 1; i >= 0; i--)
{
arr.push_back(i);
}
auto start = std::chrono::high_resolution_clock::now();
mergeSort(arr, 0, n - 1);
auto finish = std::chrono::high_resolution_clock::now();
auto time = finish - start;
return time;
}

int main()
{

int n;
cout << "Enter the value of n: ";
cin >> n;
int lb = 0;
int rb = 100;
vector<int> arr;
for (int i = 0; i < n; i++)
{
arr.push_back(rand() % (rb - lb + 1));
}
cout << endl;
auto best_time = best_merge_sort(n);
cout << "Time Taken for best case = " << (best_time / std::chrono::microseconds(1)) << "
microseconds" << endl;
auto average_time = average_merge_sort(arr, n);
cout << "Time Taken for average case = " << (average_time /
std::chrono::microseconds(1)) << " microseconds" << endl;
auto worst_time = worst_merge_sort(n);
cout << "Time Taken for worst case = " << (worst_time / std::chrono::microseconds(1)) <<
" microseconds" << endl;
cout << endl;

return 0;
}

OUTPUT: -

GRAPH: -

Merge Sort Time Graph


2750

2250

1750
Time

1250

750

250

100 500 1000 2000 5000 10000


Best Case (μ sec) 21 88 245 214 991 2400
Average Case (μ sec) 18 107 325 312 1258 2464
Worst Case (μ sec) 21 109 396 359 1365 2608
PRACTICAL – 4

AIM: Program of Merge Sort, Heap Sort, Selection Sort, Radix Sort.

4.1 HEAP SORT

Libraries Used: -

1) Random No Generator:
Library used for generating random number:
< cstdlib>,<time.h>
Function Invoked:
rand()

2) Time of Execution:
Library used for checking time of execution for each run:
<chrono>
Function Invoked:
chrono::high_resolution_clock::now();

3) Dynamic Array:
Library used for checking time of execution for each run:
<vector>

4) Plotting the outcome:


We used Excel to store the no. of inputs and time taken, and a graph is plot based on this.
Written Code: -
#include <iostream>
#include <chrono>
#include <cstdlib>
#include <vector>

using namespace std;

void heapify(vector<int> &arr, int n, int i)


{
int largest = i;
int l = 2 * i + 1;
int r = 2 * i + 2;
if (l < n && arr[l] > arr[largest])
{
largest = l;
}
if (r < n && arr[r] > arr[largest])
{
largest = r;
}
if (largest != i)
{
swap(arr[largest], arr[i]);
heapify(arr, n, largest);
}
}

void heap_Sort(vector<int> &arr, int n)


{
for (int i = n / 2 - 1; i >= 0; i--)
{
heapify(arr, n, i);
}
for (int i = n - 1; i >= 0; i--)
{
swap(arr[0], arr[i]);
heapify(arr, i, 0);
}
}

auto average_heap_sort(vector<int> arr, int n)


{
auto start = std::chrono::high_resolution_clock::now();
heap_Sort(arr, n);
auto finish = std::chrono::high_resolution_clock::now();
auto time = finish - start;
return time;
}

auto worst_heap_sort(int n)
{
vector<int> arr;
for (int i = 0; i < n; i++)
{
arr.push_back(i);
}
auto start = std::chrono::high_resolution_clock::now();
heap_Sort(arr, n);
auto finish = std::chrono::high_resolution_clock::now();
auto time = finish - start;
return time;
}

auto best_heap_sort(int n)
{
vector<int> arr;
for (int i = n; i > 0; i--)
{
arr.push_back(i);
}
auto start = std::chrono::high_resolution_clock::now();
heap_Sort(arr, n);
auto finish = std::chrono::high_resolution_clock::now();
auto time = finish - start;
return time;
}

int main()
{
int n;
cout << "Enter the value of n: ";
cin >> n;

int lb = 0;
int rb = 100;

vector<int> arr;
for (int i = 0; i < n; i++)
{
arr.push_back(rand() % (rb - lb + 1));
}
cout << endl;

auto best_time = best_heap_sort(n);


cout << "Time Taken for best case=" << (best_time / std::chrono::microseconds(1)) <<
"microseconds" << endl;

auto average_time = average_heap_sort(arr, n);


cout << "Time Taken for average case=" << (average_time / std::chrono::microseconds(1))
<< "microseconds" << endl;

auto worst_time = worst_heap_sort(n);


cout << "Time Taken for worst case=" << (worst_time / std::chrono::microseconds(1)) <<
"microseconds" << endl;

return 0;
}

OUTPUT: -
GRAPH: -

Heap Sort Time Graph


42500
37500
32500
27500
Time

22500
17500
12500
7500
2500
10 200 500 1000 5000 100000
Best Case (μ sec) 1 44 131 314 1833 31513
Average Case (μ sec) 1 49 152 321 2102 40011
Worst Case (μ sec) 1 50 191 366 2311 33028
4.2 SELECTION SORT

Libraries Used: -

1) Random No Generator:
Library used for generating random number:
< cstdlib>,<time.h>
Function Invoked:
rand()

2) Time of Execution:
Library used for checking time of execution for each run:
<chrono>
Function Invoked:
chrono::high_resolution_clock::now();

3) Dynamic Array:
Library used for checking time of execution for each run:
<vector>

4) Plotting the outcome:


We used Excel to store the no. of inputs and time taken, and a graph is plot based on this.
Written Code: -
#include <iostream>
#include <cstdlib>
#include <chrono>
#include <vector>

using namespace std;

void selection_Sort(vector<int> &arr, int n)


{
int i, j, min;
for (int i = 0; i < n - 1; i++)
{
min = i;
for (int j = i + 1; j < n; j++)
{
if (arr[j] < arr[min])
{
min = j;
}
}
if (min != i)
{
swap(arr[min], arr[i]);
}
}
}
auto average_selection_sort(vector<int> arr, int n)
{
auto start = std::chrono::high_resolution_clock::now();
selection_Sort(arr, n);
auto finish = std::chrono::high_resolution_clock::now();
auto time = finish - start;
return time;
}
auto best_selection_sort(int n)
{

vector<int> arr;
for (int i = 0; i < n; i++)
{
arr.push_back(i);
}
auto start = std::chrono::high_resolution_clock::now();
selection_Sort(arr, n);
auto finish = std::chrono::high_resolution_clock::now();
auto time = finish - start;
return time;
}
auto worst_selection_sort(int n)
{

vector<int> arr;
for (int i = n; i > 0; i--)
{
arr.push_back(i);
}
auto start = std::chrono::high_resolution_clock::now();
selection_Sort(arr, n);
auto finish = std::chrono::high_resolution_clock::now();
auto time = finish - start;
return time;
}

int main()
{

int n;
cout << "Enter the value of n: ";
cin >> n;

vector<int> arr;
for (int i = 0; i < n; i++)
{
arr.push_back(rand());
}

cout << endl;


auto best_time = best_selection_sort(n);

cout << "Time Taken for best case : " << (best_time / std::chrono::microseconds(1)) << "
microseconds" << endl;
auto average_time = average_selection_sort(arr, n);

cout << "Time Taken for average case : " << (average_time / std::chrono::microseconds(1))
<< " microseconds" << endl;

auto worst_time = worst_selection_sort(n);


cout << "Time Taken for worst case : " << (worst_time / std::chrono::microseconds(1)) <<
" microseconds" << endl;
cout << endl;

return 0;
}

OUTPUT: -

GRAPH: -

Selection Sort Time Graph


9500
8500
7500
6500
5500
Time

4500
3500
2500
1500
500
10 200 500 1000 2000

Best Case (μ sec) 1 30 779 1999 8003 NaN


Average Case (μ sec) 1 40 770 2500 8500 NaN
Worst Case (μ sec) 2 50 800 2988 8982 NaN
4.3 Radix SORT

Libraries Used: -

1) Random No Generator:
Library used for generating random number:
< cstdlib>,<time.h>
Function Invoked:
rand()

2) Time of Execution:
Library used for checking time of execution for each run:
<chrono>
Function Invoked:
chrono::high_resolution_clock::now();

3) Dynamic Array:
Library used for checking time of execution for each run:
<vector>

4) Plotting the outcome:


5) We used Excel to store the no. of inputs and time taken, and a graph is plot based on this.
Written Code: -

#include <iostream>
#include <chrono>
#include <vector>

using namespace std;

int get_Max(vector<int> &arr, int n)


{
int max = arr[0];
for (int i = 0; i < n; i++)
{
if (arr[i] > max)
{
max = arr[i];
}
}
return max;
}
void count_Sort(vector<int> &arr, int n, int exp)
{
int output[n];
int i;
int count[10] = {0};
for (int i = 0; i < n; i++)
{
count[(arr[i] / exp) % 10]++;
}
for (int i = 1; i < 10; i++)
{
count[i] += count[i - 1];
}
for (i = n - 1; i >= 0; i--)
{
output[count[(arr[i] / exp) % 10] - 1] = arr[i];
count[(arr[i] / exp) % 10]--;
}
for (int i = 0; i < n; i++)
{
arr[i] = output[i];
}
}
void radix_Sort(vector<int> &arr, int n)
{
int max = get_Max(arr, n);
for (int exp = 1; max / exp > 0; exp *= 10)
{
count_Sort(arr, n, exp);
}
}
auto average_sort(vector<int> arr, int n)
{
auto start = std::chrono::high_resolution_clock::now();
radix_Sort(arr, n);
auto finish = std::chrono::high_resolution_clock::now();
auto time = finish - start;
return time;
}
auto best_radix_sort(int n)
{
vector<int> arr;
for (int i = 0; i < n; i++)
{
arr.push_back(i);
}
auto start = std::chrono::high_resolution_clock::now();
radix_Sort(arr, n);
auto finish = std::chrono::high_resolution_clock::now();
auto time = finish - start;
return time;
}
auto worst_radix_sort(int n)
{

vector<int> arr;
for (int i = n; i > 0; i--)
{
arr.push_back(i);
}
auto start = std::chrono::high_resolution_clock::now();
radix_Sort(arr, n);
auto finish = std::chrono::high_resolution_clock::now();
auto time = finish - start;
return time;
}
int main()
{
int n;
cout << "Enter the value of n: ";
cin >> n;

int lb = 0;
int rb = 100;

vector<int> arr;
for (int i = 0; i < n; i++)
{
arr.push_back(rand() % (lb + rb + 1));
}

cout << endl;


auto best_time = best_radix_sort(n);
cout << "Time Taken for best case : " << (best_time / std::chrono::microseconds(1)) << "
microseconds" << endl;

auto average_time = average_sort(arr, n);


cout << "Time Taken for average case : " << (average_time / std::chrono::microseconds(1))
<< " microseconds" << endl;

auto worst_time = worst_radix_sort(n);


cout << "Time Taken for worst case : " << (worst_time / std::chrono::microseconds(1)) <<
" microseconds" << endl;
cout << endl;

return 0;
}
OUTPUT: -

GRAPH: -

Radix Sort Time Graph


1900
1700
1500
1300
Axis Title

1100
900
700
500
300
100
10 100 500 1000 5000 10000
Best Case (μ sec) 1 8 57 131 772 1559
Average Case (μ sec) 1 11 54 138 742 1628
Worst Case (μ sec) 1 12 55 168 838 1848
PRACTICAL-5

a. AIM: Program to find optimal solution for Fractional Knapsack Problem.

Knapsack Problem:-
Knapsack is like a container or a bag. If we have given some items with weight and profit
then we have to put items in knapsack in such a way that total value produces maximum
profit.
In fractional Knapsack problem we can divide the problem. Fractional knapsack problem can
be solved by greedy approach. The basic idea is calculating profit/weight ratio of each item
and then sort it according to that. Take item having highest ratio and add it as much as can.

For example:-
Consider arr[] = {{100,20},{60,10},{120,30}} and W=50
First of all calculate profit/weight ratio of each item.
100/20 = 5
60/10 = 6
120/30 = 4
Now sort them: {{60,10},{100,20},{120,30}}

Iteration:-
For i = 0 weight=10 <50 so add it in the knapsack. W becomes 40
For i = 1 weight=20<40 so add it in the knapsack. W becomes 20
For i = 2 weight=30>20 fraction of 30 will be added that is 20/30 = 2/3 fraction of item in the
knapsack.
Calculating profit: 60 + 100+ 2/3*120 = 240 which is the maximum profit.
Algorithm:-
Begin
Take an array of structure item
Declare profit, weight, knapsack weight and density
Calculate density = profit/weight for each item
Sort the items of array in decreasing order
Add weight of items of array in knapsack until it is full (Total value <=W)
End

CODE:-
#include <iostream>
#include <bits/stdc++.h>
using namespace std;

typedef struct
{
int v;
int w;
float d;
} Item;

void input(Item items[], int sizeOfItems)


{
cout << "Enter total " << sizeOfItems << " item's values and weight" << endl;
for (int i = 0; i < sizeOfItems; i++)
{
cout << "Enter " << i + 1 << " V ";
cin >> items[i].v;
cout << "Enter " << i + 1 << " W ";
cin >> items[i].w;
}
}

void display(Item items[], int sizeOfItems)


{
int i;
cout << "values: ";
for (i = 0; i < sizeOfItems; i++)
{
cout << items[i].v << "\t";
}
cout << endl
<< "weight: ";
for (i = 0; i < sizeOfItems; i++)
{
cout << items[i].w << "\t";
}
cout << endl;
}

bool compare(Item i1, Item i2)


{
return (i1.d > i2.d);
}

float knapsack(Item items[], int sizeOfItems, int W)


{
int i, j;
float totalValue = 0, totalWeight = 0;
for (i = 0; i < sizeOfItems; i++)
{
items[i].d = (float)items[i].v / items[i].w; // typecasting done (v is int and w is also int so
we get final value of d as int)
}
sort(items, items + sizeOfItems, compare);
cout << "values : ";

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


{
cout << items[i].v << "\t";
}
cout << endl << "weights: ";

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


{
cout << items[i].w << "\t";
}
cout << endl << "ratio : ";

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


{
cout << items[i].d << "\t";
}
cout << endl;

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


{
if (totalWeight + items[i].w <= W)
{
totalValue += items[i].v;
totalWeight += items[i].w;
}
else
{
int wt = W - totalWeight;
totalValue += (wt * items[i].d);
totalWeight += wt;
break;
}
}
cout << "Total weight in bag " << totalWeight << endl;
return totalValue;
}

int main()
{
int W, n;
cout << "enter n: ";
cin >> n;

Item items[n];
input(items, n);

cout << "Entered data \n";


display(items, n);

cout << "Enter Knapsack weight \n";


cin >> W;

float mxVal = knapsack(items, n, W);


cout << "Max value for " << W << " weight is " << mxVal;
}

Output :
b. AIM: Program to find Minimum Cost Spanning tree using prims algorithm.

Prim’s Algorithm:-
Prim’s algorithm is the minimum spanning tree algorithm that takes graph as input and find
subset of edges of that graph which forms tree and includes every vertex, has the minimum
sum of weights among all the trees formed from graph.

Algorithm:-
Select a starting vertex
Repeat steps 3 and 4 until there are fringe vertices
Select an edge ‘e’ connecting the tree vertex and fringe vertex that has minimum weight.
Add the selected edge and the vertex to the minimum spanning tree T
Exit

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

class Solution
{
public:
int spanningTree(int V, vector<vector<int>> adj[])
{
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
vector<int> vis(V, 0);

pq.push({0, 0});
int sum = 0;

while (!pq.empty())
{
auto it = pq.top();
pq.pop();
int node = it.second;
int wt = it.first;
if (vis[node] == 1)
continue;
vis[node] = 1;
sum += wt;
for (auto it : adj[node])
{
int adjNode = it[0];
int edW = it[1];
if (!vis[adjNode])
{
pq.push({edW, adjNode});
}
}
}
return sum;
}
};

int main()
{
int V = 5;
vector<vector<int>> edges = {{0, 1, 2}, {0, 2, 1}, {1, 2, 1}, {2, 3, 2}, {3, 4, 1}, {4, 2, 2}};
vector<vector<int>> adj[V];

for (auto it : edges)


{
vector<int> tmp(2);
tmp[0] = it[1];
tmp[1] = it[2];
adj[it[0]].push_back(tmp);
tmp[0] = it[0];
tmp[1] = it[2];
adj[it[1]].push_back(tmp);
}

Solution obj;
int sum = obj.spanningTree(V, adj);
cout << "The sum of all the edge weights: " << sum << endl;

return 0;
}

Output:-
PRACTICAL-6

a. AIM: Program to find minimum cost Spanning tree using Kruskal Algorithm.
In Kruskal’s algorithm sort all edges of given graph in increasing order. Then keeps on
adding new edges and nodes in minimum spanning tree if newly added doesn’t form cycle. It
picks the minimum weighted edge at first and the maximum weighted edge at last.

STEPS:
Sort all the edges in non-decreasing order of their weight.
Pick the smallest edge. Check if it forms a cycle with the spanning tree formed so far. If the
cycle is not formed, include this edge. Else, discard it.
Repeat step#2 until there are (V-1) edges in the spanning tree.

CODE:-
#include <iostream>
#include <algorithm>
using namespace std;

class Edge
{
public:
int source;
int dest;
int weight;
};

bool comp(Edge e1, Edge e2)


{
return e1.weight < e2.weight;
}

int findparent(int v, int parent[])


{
if (parent[v] == v)
{
return v;
}
findparent(parent[v], parent);
}

void kruskals(Edge input[], int n, int E)


{
sort(input, input + E, comp);

Edge output[n - 1];


int parent[n];

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


{
parent[i] = i;
}

int count = 0;
int i = 0;

while (count != n - 1)
{
Edge currentedge = input[i];
int sourceparent = findparent(currentedge.source, parent);
int destparent = findparent(currentedge.dest, parent);
if (sourceparent != destparent)
{
output[count] = currentedge;
count++;
parent[sourceparent] = destparent;
}
i++;
}
cout << "Result is:" << endl;

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


{
if (output[i].source < output[i].dest)
{
cout << output[i].source << " " << output[i].dest << " " << output[i].weight << endl;
}
else
{
cout << output[i].dest << " " << output[i].source << " " << output[i].weight << endl;
}
}
}

int main()
{
int n, E;
cout << "Enter number of vertices and edges:";
cin >> n >> E;

Edge input[E];
for (int i = 0; i < E; i++)
{
cout << "Enter " << i + 1 << " connection:";
cin >> input[i].source >> input[i].dest >> input[i].weight;
}

kruskals(input, n, E);
return 0;
}

Output :-
b. AIM: Program to find Minimum Cost Spanning tree using prims algorithm.

Djikstra Algorithm:-
Program to implement Djikstra Algorithm
The idea is to generate a SPT (shortest path tree) with a given source as a root. Maintain an
Adjacency Matrix with two sets,
 one set contains vertices included in the shortest-path tree,
 other set includes vertices not yet included in the shortest-path tree.
At every step of the algorithm, find a vertex that is in the other set (set not yet included)
and has a minimum distance from the source.

CODE:-
#include <iostream>
#include <limits.h>
using namespace std;

#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 Distance from source" << endl;
for (int i = 0; i < V; i++)
{
cout << i << " " << 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, 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:-
PRACTICAL-7
a. AIM: Write a program to implement 0/1 Knapsack Problem.

CODE:-
#include <iostream>
using namespace std;
int max(int x, int y)
{
return (x > y) ? x : y;
}
int knapSack(int W, int w[], int v[], int n)
{
int i, wt;
int K[n + 1][W + 1];
for (i = 0; i <= n; i++)
{
for (wt = 0; wt <= W; wt++)
{
if (i == 0 || wt == 0)
K[i][wt] = 0;
else if (w[i - 1] <= wt)
K[i][wt] = max(v[i - 1] + K[i - 1][wt - w[i - 1]], K[i - 1][wt]);
else
K[i][wt] = K[i - 1][wt];
}
}
return K[n][W];
}
int main()
{
cout << "Enter the number of items in a Knapsack:";
int n, W;
cin >> n;
int v[n], w[n];
for (int i = 0; i < n; i++)
{
cout << "Enter value and weight for item " << i << ":";
cin >> v[i];
cin >> w[i];
}
cout << "Enter the capacity of knapsack: ";
cin >> W;
cout << knapSack(W, w, v, n);
return 0;
}

Output:-
b. AIM: Write a program to solve All pairs shortest path problem using Floyd-
Warshall Algorithm.

CODE:-
#include <iostream>
#include <cstdlib>
#define max 10
#define infi 999
using namespace std;
int p[max][max];
void allpairshort(int a[max][max], int n)
{
int k, i, j;
for (k = 0; k < n; k++)
{
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
if (a[i][k] + a[k][j] < a[i][j])
{
a[i][j] = a[i][k] + a[k][j];
p[i][j] = k;
}
}
}
}
}

void shortest(int i, int j)


{
int k = p[i][j];
if (k > 0)
{
shortest(i, k);
cout << " " << k << " ";
shortest(k, j);
}
}

void findpath(int a[max][max], int i, int j, int n)


{
cout << "Path from " << i << " to " << j << ":";
if (a[i][j] < infi)
{
cout << " " << i << " ";
shortest(i, j);
cout << " " << j << " ";
}
}
int main()
{
int i, j;
int a[][10] = {
{0, 10, infi, 30, 100},
{infi, 0, 50, infi, infi},
{infi, infi, 0, infi, 10},
{infi, infi, 20, 0, 60},
{infi, infi, infi, infi, 0},
};
allpairshort(a, 5);
findpath(a, 0, 4, 5);
return 0;
}

Output:-
PRACTICAL-8
a. AIM: Write a program to solve 8-queen problem using backtracking
approach

CODE:-
#include <bits/stdc++.h>
using namespace std;
int countt = 0;
void print(int board[][4])
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
cout << board[i][j] << " ";
}
cout << endl;
}
cout << "-----------------\n";
}
bool isValid(int board[][4], int row, int col)
{

for (int i = col; i >= 0; i--)


{
if (board[row][i])
return false;
}
int i = row, j = col;
while (i >= 0 && j >= 0)
{
if (board[i][j])
return false;
i--;
j--;
}
i = row;
j = col;

while (i < 4 && j >= 0)


{
if (board[i][j])
return false;
i++;
j--;
}
return true;
}

void ninjaQueens(int board[][4], int currentColumn)


{
if (currentColumn >= 4)
return;

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


{
if (isValid(board, i, currentColumn))
{
board[i][currentColumn] = 1;
if (currentColumn == 3)
{
print(board);
countt++;
}

ninjaQueens(board, currentColumn + 1);

board[i][currentColumn] = 0;
}
}
}
int main()
{

int board[4][4] = {{0, 0, 0, 0},


{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}};
ninjaQueens(board, 0);

cout << countt << endl;


return 0;
}

Output:-
b. AIM: Write a program to solve Sum of Subsets problem using backtracking
approach.

CODE:-
#include <iostream>
#include <vector>
using namespace std;
bool isSubsetSum(vector<int> &set, int n, int targetSum, vector<int> &subset)
{
if (targetSum == 0)
{
for (int i = 0; i < subset.size(); i++)
{
cout << subset[i] << " ";
}
cout << endl;
return true;
}
if (n == 0 || targetSum < 0)
{
return false;
}
if (isSubsetSum(set, n - 1, targetSum, subset))
{
return true;
}
subset.push_back(set[n - 1]);
if (isSubsetSum(set, n - 1, targetSum - set[n - 1], subset))
{
return true;
}
subset.pop_back();

return false;
}

int main()
{
vector<int> set = {3, 34, 4, 12, 5, 2};
int targetSum;
cout << "Enter the targetSum: ";
cin >> targetSum;

vector<int> subset;

if (isSubsetSum(set, set.size(), targetSum, subset))


{
cout << "Subset with the given sum exists." << endl;
}
else
{
cout << "No subset with the given sum exists." << endl;
}

return 0;
}

Output:-

You might also like