0% found this document useful (0 votes)
5 views43 pages

Daafileeeword

The document contains multiple C++ programs demonstrating various algorithms, including linear search, selection sort, bubble sort, insertion sort, binary search, ternary search, merge sort, quick sort, randomized quick sort, heap sort, count sort, breadth-first search, depth-first search, and Prim's algorithm for finding a minimum spanning tree. Each program includes the implementation details, main function, and expected output. The programs serve as educational examples for understanding fundamental algorithms and data structures.

Uploaded by

Bolt Biro
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)
5 views43 pages

Daafileeeword

The document contains multiple C++ programs demonstrating various algorithms, including linear search, selection sort, bubble sort, insertion sort, binary search, ternary search, merge sort, quick sort, randomized quick sort, heap sort, count sort, breadth-first search, depth-first search, and Prim's algorithm for finding a minimum spanning tree. Each program includes the implementation details, main function, and expected output. The programs serve as educational examples for understanding fundamental algorithms and data structures.

Uploaded by

Bolt Biro
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/ 43

PROGRAM-1

Write a program for the implementation of linear search.

#include<iostream>
using namespace std;
int linearSearch(int arr[],int size,int key){
for(int i = 0;i<size;i++){
if(arr[i]==key){
return i;
}
}
return -1;
}
int main(){
int arr[]={1,2,3,4,5,6,7,8,9};
int size=sizeof(arr)/sizeof(arr[0]);
cout<<linearSearch(arr,size,4);
return 0;
}

OUTPUT

PROGRAM-2
Write a program for the implementation of selection sort.
#include <iostream>
using namespace std;

void selectionSort(int arr[], int n) {


for (int i = 0; i < n - 1; i++) {
int minIdx = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIdx]) {
minIdx = j;
}
}
if (minIdx != i) {
swap(arr[i], arr[minIdx]);
}
}
}
int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr) / sizeof(arr[0]);
selectionSort(arr, n);
cout << "Sorted array: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}

OUTPUT

Sorted array: 11 12 22 25 64

PROGRAM-3
Write a program for the implementation of Bubble sort.
#include<iostream>
using namespace std;
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]);
}
}
}
}
int main(){
int arr[]={2,3,4,2,5,8,4,7};
int n= sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr,n);
for(int i: arr){
cout<<i<<" ";
}

OUTPUT

22344578

PROGRAM-4
Write a program for the implementation of Insertion sort.

#include <iostream>
using namespace std;
void insertionSort(int arr[], int n) {
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;

while (j >= 0 && arr[j] > key) {


arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr) / sizeof(arr[0]);
insertionSort(arr, n);
cout << "Sorted array: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}

OUTPUT

Sorted array: 11 12 22 25 64

PROGRAM-5
Write a program for the implementation of Binary search.

#include <iostream>
using namespace std;
int binarySearch(int arr[], int n, int key) {
int low = 0, high = n - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == key)
return mid;
else if (arr[mid] < key)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
int main() {
int arr[]={1,2,3,4,5,6,7,8,9};
int key=8;
int n=sizeof(arr)/sizeof(arr[0]);
int result = binarySearch(arr, n, key);
if (result != -1)
cout << result << endl;
else
cout << -1 << endl;
return 0;
}

OUTPUT

7
PROGRAM-6
Write a program for the implementation of ternary search.

#include <iostream>
using namespace std;
int ternarySearch(int arr[], int n, int key) {
int low = 0, high = n - 1;
while (low <= high) {
int mid1 = low + (high - low) / 3;
int mid2 = high - (high - low) / 3;
if (arr[mid1] == key)
return mid1;
if (arr[mid2] == key)
return mid2;
if (key < arr[mid1])
high = mid1 - 1;
else if (key > arr[mid2])
low = mid2 + 1;
else {
low = mid1 + 1;
high = mid2 - 1;
}
}
return -1;
}
int main() {
int arr[]={1,2,3,4,5,6,7,8,9};
int key=8;
int n=sizeof(arr)/sizeof(arr[0]);
int result = ternarySearch(arr, n, key);
if (result != -1)
cout << result << endl;
else
cout << -1 << endl;
return 0;
}

OUTPUT

7
PROGRAM-7
Write a program for the implementation of Merge sort.

#include<iostream>
using namespace std;
void merge(int arr[],int si,int mid,int ei);
void mergeSort(int arr[],int si,int ei){
if(si>=ei){return;}
int mid=si+(ei-si)/2;
mergeSort(arr, si, mid);
mergeSort(arr, mid+1, ei);
merge(arr,si,mid,ei);
}
void merge(int arr[],int si,int mid,int ei){
int *temp=new int[ei-si+1];
int i = si;
int j = mid+1;
int k =0;
while(i<=mid&&j<=ei){
if(arr[i]<arr[j]){
temp[k++]=arr[i++];
}
else{
temp[k++]=arr[j++];
}

}
while(i<=mid){
temp[k++]=arr[i++];
}
while(j<=ei){
temp[k++]=arr[j++];
}
for(k=0,i=si;k<ei-si+1;i++,k++){
arr[i]=temp[k];
}
}
int main(){
int arr[]={2,3,4,3,2,-2,98,-9,3,4};
int n = sizeof(arr)/sizeof(arr[0]);
mergeSort(arr,0,n-1);
for(int i:arr){
cout<<i<<" ";
}
return 0;
}

OUTPUT

-9 -2 2 2 3 3 3 4 4 98
PROGRAM-8
Write a program for the implementation of Quick sort.

#include<iostream>
using namespace std;
int partition(int arr[],int si,int ei);
void quickSort(int arr[],int si,int ei){
if(si>=ei)return ;
int pIdx=partition(arr,si,ei);
quickSort(arr, si, pIdx-1);
quickSort(arr, pIdx+1, ei);
}
int partition(int arr[],int si,int ei){
int pivot = arr[ei];
int i=si-1;
for(int j=si;j<ei;j++){
if(arr[j]<=pivot){
i++;
int temp=arr[j];
arr[j]=arr[i];
arr[i]=temp;
}
}
i++;
int temp=pivot;
arr[ei]=arr[i];
arr[i]=temp;
return i;
}
int main(){
int arr[]={2,3,5,2,5,7,8,4,7,4};
int n=sizeof(arr)/sizeof(arr[0]);
quickSort(arr,0,n-1);
for(int i: arr){
cout<<i<<" ";
}
return 0;
}

OUTPUT

2234455778

PROGRAM-9
Write a program for the implementation of Randomized quick sort.

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

void swap(int* a, int* b) {


int temp = *a;
*a = *b;
*b = temp;
}

int get_random_index(int low, int high) {


return low + rand() % (high - low + 1);
}

int partition(int arr[], int low, int high) {


int pivot_index = get_random_index(low, high);
swap(&arr[pivot_index], &arr[high]);
int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j] < pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return i + 1;
}

void randomized_quicksort(int arr[], int low, int high) {


if (low < high) {
int pivot_index = partition(arr, low, high);
randomized_quicksort(arr, low, pivot_index - 1);
randomized_quicksort(arr, pivot_index + 1, high);
}
}

void print_array(int arr[], int size) {


for (int i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}

int main() {
srand(time(0));
int arr[] = {43, 28, 56, 90, 32, 22, 41};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Original array: ";
print_array(arr, n);

randomized_quicksort(arr, 0, n - 1);

cout << "Sorted array: ";


print_array(arr, n);

return 0;
}

OUTPUT

Original array: 43 28 56 90 32 22 41
Sorted array: 22 28 32 41 43 56 90
PROGRAM-10
Write a program for the implementation of Heap sort.

#include <iostream>
using namespace std;
void heapify(int arr[], int n, int i) {
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < n && arr[left] > arr[largest])
largest = left;
if (right < n && arr[right] > arr[largest])
largest = right;
if (largest != i) {
swap(arr[i], arr[largest]);
heapify(arr, n, largest);
}
}
void heapSort(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);
}
}
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
}
int main() {
int arr[] = {12, 11, 13, 5, 6, 7};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Original array: ";
printArray(arr, n);
heapSort(arr, n);
cout << "Sorted array: ";
printArray(arr, n);
return 0;
}

OUTPUT

Original array: 12 11 13 5 6 7
Sorted array: 5 6 7 11 12 13
PROGRAM-11
Write a program for the implementation of Count sort and Compute its Complexity.

#include<iostream>
using namespace std;
void countSort(int arr[],int n){
int maxx=-1;
for(int i=0;i<n;i++){
if(maxx<arr[i]){
maxx=arr[i];
}
}
int *x=new int[maxx+1];
for(int i = 0;i<n;i++){
x[arr[i]]++;
}
int j=0;
for(int i=0;i<maxx+1;i++){
while(x[i]>0){
arr[j++]=i;
x[i]--;
}
}
}
int main(){
int arr[]={2,3,5,2,5,7,8,4,7,4};
int n=sizeof(arr)/sizeof(arr[0]);
countSort(arr,n);
for(int i: arr){
cout<<i<<" ";
}
return 0;
}

OUTPUT

2234455778
PROGRAM-12
Write a program for the implementation of Tree Traversal- Breadth First Search.

#include <iostream>
#include <queue>
#include <vector>
using namespace std;
void bfs(vector<vector<int>>& adjMatrix, int start) {
int n = adjMatrix.size();
vector<bool> visited(n, false);
queue<int> q;
visited[start] = true;
q.push(start);
while (!q.empty()) {
int node = q.front();
q.pop();
cout << node << " ";

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


if (adjMatrix[node][i] && !visited[i]) {
visited[i] = true;
q.push(i);
}
}
}
}
int main() {
int n = 4;
vector<vector<int>> adjMatrix = {
{0, 1, 1, 0},
{1, 0, 0, 1},
{1, 0, 0, 1},
{0, 1, 1, 0}
};
int start = 0;
bfs(adjMatrix, start);
return 0;
}

OUTPUT

0123
PROGRAM-13
Write a program for the implementation of Tree Traversal- Depth First Search.

#include <iostream>
#include <vector>
using namespace std;
void dfs(vector<vector<int>>& adjMatrix, int node, vector<bool>& visited) {
visited[node] = true;
cout << node << " ";
for (int i = 0; i < adjMatrix.size(); i++) {
if (adjMatrix[node][i] && !visited[i]) {
dfs(adjMatrix, i, visited);
}
}
}
int main() {
int n = 4;
vector<vector<int>> adjMatrix = {
{0, 1, 1, 0},
{1, 0, 0, 1},
{1, 0, 0, 1},
{0, 1, 1, 0}
};
int start = 0;
vector<bool> visited(n, false);
dfs(adjMatrix, start, visited);
return 0;
}

OUTPUT

0132
PROGRAM-14
Write a program to convert graph into spanning tree- using Prim’s Algorithm.

#include <iostream>
#include <climits>
using namespace std;

#define V 5

int minKey(int key[], bool mstSet[]) {


int min = INT_MAX, min_index;
for (int v = 0; v < V; v++) {
if (!mstSet[v] && key[v] < min) {
min = key[v];
min_index = v;
}
}
return min_index;
}

void printMST(int parent[], int graph[V][V]) {


cout << "Edge \tWeight\n";
for (int i = 1; i < V; i++)
cout << parent[i] << " - " << i << " \t" << graph[i][parent[i]] << endl;
}

void primMST(int graph[V][V]) {


int parent[V];
int key[V];
bool mstSet[V];

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


key[i] = INT_MAX;
mstSet[i] = false;
}

key[0] = 0;
parent[0] = -1;

for (int count = 0; count < V - 1; count++) {


int u = minKey(key, mstSet);
mstSet[u] = true;
for (int v = 0; v < V; v++) {
if (graph[u][v] && !mstSet[v] && graph[u][v] < key[v]) {
parent[v] = u;
key[v] = graph[u][v];
}
}
}

printMST(parent, graph);
}
int main() {
int graph[V][V] = {
{0, 2, 0, 6, 0},
{2, 0, 3, 8, 5},
{0, 3, 0, 0, 7},
{6, 8, 0, 0, 9},
{0, 5, 7, 9, 0}
};
primMST(graph);
return 0;
}

OUTPUT

Edge Weight
0-1 2
1-2 3
0-3 6
1-4 5
PROGRAM-15
Write a program to convert graph into spanning tree- using Kruskal’s Algorithm.

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Edge {
int src;
int dest;
int weight;
};
int findParent(int node, vector<int>& parent) {
if (parent[node] == node)
return node;
return findParent(parent[node], parent);
}
void unionSets(int u, int v, vector<int>& parent) {
parent[findParent(u, parent)] = findParent(v, parent);
}
void kruskal(int V, vector<Edge>& edges) {

sort(edges.begin(), edges.end(), [](Edge a, Edge b) {


return a.weight < b.weight;
});
vector<int> parent(V);
for (int i = 0; i < V; i++) {
parent[i] = i;
}
vector<Edge> mst;
int mstWeight = 0;
for (Edge& edge : edges) {
if (findParent(edge.src, parent) != findParent(edge.dest, parent)) {
mst.push_back(edge);
mstWeight += edge.weight;
unionSets(edge.src, edge.dest, parent);
}
}
for (Edge& edge : mst) {
cout<<edge.src<<" - "<<edge.dest<<" = "<< edge.weight << endl;
}
cout << mstWeight << endl;
}
int main() {
int V = 4;

vector<Edge> edges = {
{0, 1, 10},
{0, 2, 6},
{0, 3, 5},
{1, 3, 15},
{2, 3, 4}
};
kruskal(V, edges);
return 0;
}

OUTPUT

2-3=4
0-3=5
0 - 1 = 10
19
PROGRAM-16
Write a program for the implementation of Network Flow.

#include <iostream>
#include <climits>
#include <queue>
#include <vector>
using namespace std;
#define V 6
bool bfs(int rGraph[V][V], int s, int t, int parent[]) {
bool visited[V] = {false};
queue<int> q;
q.push(s);
visited[s] = true;
parent[s] = -1;
while (!q.empty()) {
int u = q.front(); q.pop();

for (int v = 0; v < V; v++) {


if (!visited[v] && rGraph[u][v] > 0) {
q.push(v);
parent[v] = u;
visited[v] = true;
}
}
}
return visited[t];
}
int fordFulkerson(int graph[V][V], int s, int t) {
int u, v;
int rGraph[V][V];
for (u = 0; u < V; u++)
for (v = 0; v < V; v++)
rGraph[u][v] = graph[u][v];
int parent[V];
int max_flow = 0;
while (bfs(rGraph, s, t, parent)) {
int path_flow = INT_MAX;
for (v = t; v != s; v = parent[v]) {
u = parent[v];
path_flow = min(path_flow, rGraph[u][v]);
}
for (v = t; v != s; v = parent[v]) {
u = parent[v];
rGraph[u][v] -= path_flow;
rGraph[v][u] += path_flow;
}
max_flow += path_flow;
}
return max_flow;
}
int main() {
int graph[V][V] = {
{0, 16, 13, 0, 0, 0},
{0, 0, 10, 12, 0, 0},
{0, 4, 0, 0, 14, 0},
{0, 0, 9, 0, 0, 20},
{0, 0, 0, 7, 0, 4},
{0, 0, 0, 0, 0, 0}
};
int source = 0, sink = 5;
cout << "Maximum Flow: " << fordFulkerson(graph, source, sink) << endl;
return 0;
}

OUTPUT

Maximum Flow: 23
PROGRAM-17
Write a program to find shortest path using Dijkstra’s Algorithm.

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int graph[100][100];
int n ;
void display(int dist[] , int parent[] ){
for(int i =0 ;i < n ;i++){
int temp = parent[i] ;
cout<<i << " <- " ;
while(temp!=-1)
{
cout<< temp << " <- " ;
temp = parent[temp] ;
}
cout<<endl;
cout<<"::::Distance = " << dist[i] ;
cout<<endl;
}
}
int getMin(int dist[],bool visited[]){
int key = 0;
int min=INT_MAX;
for(int i =0;i<n;i++){
if(!visited[i]&& dist[i]<min){
min=dist[i];
key=i;
}
}
return key;
}
void dijkstra(int source){
int parent[100],dist[100];
bool visited[100]={0};
fill(dist,dist+n,INT_MAX);
dist[source]=0;
parent[source]=-1;

for(int i=0;i<n-1;i++){
int u = getMin(dist,visited);
visited[u]=1;
cout<<"min = "<<u<<endl;
for(int v=0;v<n;v++){
if(!visited[v]&&graph[u][v]&&dist[u]+graph[u][v]<dist[v]){
dist[v]=dist[u]+graph[u][v];
parent[v]=u;
}
}
}
display(dist,parent);
}

int main(){
cout<<"Enter n : " ;
cin>>n ;
cout<<"Enter graph matrix : \n" ;
for(int i = 0 ;i < n ; i++){
for(int j = 0 ; j< n ; j++)cin>>graph[i][j] ;
}
int src ;
cout<<"\nEnter source : " ; cin>>src ;
dijkstra(src) ;

OUTPUT

Enter n : 5
Enter graph matrix :
0 10 0 0 5
00102
00040
70600
03920

Enter source : 0
min = 0
min = 4
min = 3
min = 1
0 <-
::::Distance = 0
1 <- 4 <- 0 <-
::::Distance = 8
2 <- 1 <- 4 <- 0 <-
::::Distance = 9
3 <- 4 <- 0 <-
::::Distance = 7
4 <- 0 <-
::::Distance = 5
PROGRAM-18
Write a program for the implementation of Topological sort.

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int n;
vector<vector<int>> adjMatrix;
vector<bool> visited;
vector<int> ans;

void dfs(int v) {
visited[v] = true;
for (int u = 0; u < n; ++u) {
if (adjMatrix[v][u] && !visited[u]) {
dfs(u);
}
}
ans.push_back(v);
}

void topological_sort() {
visited.assign(n, false);
ans.clear();
for (int i = 0; i < n; ++i) {
if (!visited[i]) {
dfs(i);
}
}
reverse(ans.begin(), ans.end());
}
int main() {
n = 6;
adjMatrix.assign(n, vector<int>(n, 0));
adjMatrix[5][2] = 1;
adjMatrix[5][0] = 1;
adjMatrix[4][0] = 1;
adjMatrix[4][1] = 1;
adjMatrix[2][3] = 1;
adjMatrix[3][1] = 1;

topological_sort();

cout << "Topological Sort:\n";


for (int v : ans) {
cout << v << " ";
}
cout << endl;
return 0;}

OUTPUT

Topological Sort:
542310
PROGRAM-19
Write a program for the implementation of Greedy- 0/1 knapsack.

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void knapsack(vector<int>& profit, int max_weight, vector<int>& weight) {
int n = profit.size();
vector<pair<double, int>> ratio(n);
for (int i = 0; i < n; i++) {
ratio[i] = { (double)profit[i] / weight[i], i };
}
sort(ratio.begin(), ratio.end(), greater<>());
int max_profit = 0;
for (int i = 0; i < n; i++) {
int idx = ratio[i].second;
if (weight[idx] <= max_weight) {
max_profit += profit[idx];
max_weight -= weight[idx];
}
}
cout << max_profit << endl;
}
int main() {
int n;
cin >> n;
vector<int> profit(n);
vector<int> weight(n);
for (int i = 0; i < n; i++) {
cin >> profit[i];
}
for (int i = 0; i < n; i++) {
cin >> weight[i];
}
int max_weight;
cin >> max_weight;

knapsack(profit, max_weight, weight);


return 0;
}

OUTPUT
3
60 100 120
10 20 30 50
160
PROGRAM-20
Write a program for the implementation of Greedy- Fractional knapsack.

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void fractional_knapsack(vector<int>& profit, int max_weight, vector<int>&
weight) {
int n = profit.size();
vector<pair<double, int>> ratio(n);
for (int i = 0; i < n; i++) {
ratio[i] = { (double)profit[i] / weight[i], i };
}
sort(ratio.begin(), ratio.end(), greater<>());
double max_profit = 0.0;
for (int i = 0; i < n; i++) {
int idx = ratio[i].second;
if (weight[idx] <= max_weight) {
max_profit += profit[idx];
max_weight -= weight[idx];
} else {
max_profit += profit[idx] * ((double)max_weight / weight[idx]);
break;
}
}
cout << max_profit << endl;
}
int main() {
int n;
cin >> n;
vector<int> profit(n);
vector<int> weight(n);
for (int i = 0; i < n; i++) {
cin >> profit[i];
}
for (int i = 0; i < n; i++) {
cin >> weight[i];
}
int max_weight;
cin >> max_weight;
fractional_knapsack(profit, max_weight, weight);
return 0;
}

OUTPUT
3
60 100 120
10 20 30
50
240

PROGRAM-21
Write a program for the implementation of Job Sequencing.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

struct Job {
int id;
int deadline;
int profit;
};

bool compare(Job a, Job b) {


return a.profit > b.profit;
}

int findMaxDeadline(vector<Job>& jobs) {


int maxDeadline = jobs[0].deadline;
for (size_t i = 1; i < jobs.size(); i++) {
if (jobs[i].deadline > maxDeadline)
maxDeadline = jobs[i].deadline;
}
return maxDeadline;
}

void jobSequencing(vector<Job>& jobs) {


sort(jobs.begin(), jobs.end(), compare);
int maxDeadline = findMaxDeadline(jobs);
vector<int> slot(maxDeadline, -1);
int totalProfit = 0;

cout << "Selected jobs: ";


for (size_t i = 0; i < jobs.size(); i++) {
for (int j = jobs[i].deadline - 1; j >= 0; j--) {
if (slot[j] == -1) {
slot[j] = jobs[i].id;
totalProfit += jobs[i].profit;
cout << "J" << jobs[i].id << " ";
break;
}
}
}
cout << "\nTotal Profit = " << totalProfit << endl;
}

int main() {
vector<Job> jobs = {
{1, 2, 100},
{2, 1, 19},
{3, 2, 27},
{4, 1, 25},
{5, 3, 15}
};

jobSequencing(jobs);
return 0;
}

OUTPUT

Selected jobs: J1 J3 J5
Total Profit = 142
PROGRAM-22
Write a program for the implementation of Optimal Merge Pattern.

#include <iostream>
#include <vector>
using namespace std;

void swap(int &a, int &b) {


int temp = a;
a = b;
b = temp;
}

void minHeapify(vector<int> &heap, int n, int i) {


int smallest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;

if (left < n && heap[left] < heap[smallest])


smallest = left;
if (right < n && heap[right] < heap[smallest])
smallest = right;

if (smallest != i) {
swap(heap[i], heap[smallest]);
minHeapify(heap, n, smallest);
}
}

void buildMinHeap(vector<int> &heap, int n) {


for (int i = n / 2 - 1; i >= 0; i--)
minHeapify(heap, n, i);
}

int extractMin(vector<int> &heap, int &n) {


int root = heap[0];
heap[0] = heap[n - 1];
n--;
heap.pop_back();
minHeapify(heap, n, 0);
return root;
}

void insertHeap(vector<int> &heap, int &n, int key) {


heap.push_back(key);
n++;
int i = n - 1;
while (i != 0 && heap[(i - 1) / 2] > heap[i]) {
swap(heap[i], heap[(i - 1) / 2]);
i = (i - 1) / 2;
}
}

int optimalMerge(vector<int> &files) {


int n = files.size();
buildMinHeap(files, n);
int totalCost = 0;

while (n > 1) {
int first = extractMin(files, n);
int second = extractMin(files, n);
int cost = first + second;
totalCost += cost;
insertHeap(files, n, cost);
}
return totalCost;
}

int main() {
vector<int> files = {20, 30, 10, 5, 30};
int minCost = optimalMerge(files);
cout << "Minimum total cost of merging = " << minCost << endl;
return 0;
}

OUTPUT

Minimum total cost of merging = 205


PROGRAM-23
Write a program for the implementation of Optimal Storage on Tape.

#include <iostream>
#include <algorithm>
using namespace std;

int compare(const void *a, const void *b) {


return (*(int *)a - *(int *)b);
}

int optimalStorage(int programs[], int n) {


qsort(programs, n, sizeof(int), compare);
int totalTime = 0;
int currentTime = 0;
for (int i = 0; i < n; i++) {
currentTime += programs[i];
totalTime += currentTime;
}
return totalTime;
}

int main() {
int programs[] = {5, 10, 3, 8};
int n = sizeof(programs) / sizeof(programs[0]);
int totalRetrievalTime = optimalStorage(programs, n);
cout << "Minimum total retrieval time = " << totalRetrievalTime << endl;
return 0;
}

OUTPUT

Minimum total retrieval time = 53


PROGRAM-24
Write a program for the implementation of Bin Packaging.

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

#define MAX 100

int compare(const void *a, const void *b) {


return (*(int *)b - *(int *)a);
}

int binPackingFFD(int weights[], int n, int binCapacity) {


vector<int> bins(MAX, 0);
int binCount = 0;
qsort(weights, n, sizeof(int), compare);
for (int i = 0; i < n; i++) {
int j;
for (j = 0; j < binCount; j++) {
if (bins[j] + weights[i] <= binCapacity) {
bins[j] += weights[i];
break;
}
}
if (j == binCount) {
bins[binCount] = weights[i];
binCount++;
}
}
return binCount;
}

int main() {
int weights[] = {4, 8, 1, 4, 2, 1};
int n = sizeof(weights) / sizeof(weights[0]);
int binCapacity = 10;
int binsUsed = binPackingFFD(weights, n, binCapacity);
cout << "Minimum number of bins required = " << binsUsed <<
endl;
return 0;
}

OUTPUT

Minimum number of bins required = 2


PROGRAM-25
Write program for the implementation of Dynamic Programing:-All pair shortest path .

#include <iostream>
#include <vector>
#include <climits>
using namespace std;

#define V 4
#define INF 99999

void printSolution(const vector<vector<int>>& dist) {


cout << "Shortest distances between every pair of vertices:\n";
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (dist[i][j] == INF)
cout << " INF";
else
cout << " " << dist[i][j];
}
cout << "\n";
}
}

void floydWarshall(const vector<vector<int>>& graph) {


vector<vector<int>> dist(V, vector<int>(V));

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


for (int j = 0; j < V; j++) {
dist[i][j] = graph[i][j];
}
}

for (int k = 0; k < V; k++) {


for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (dist[i][k] != INF && dist[k][j] != INF &&
dist[i][k] + dist[k][j] < dist[i][j]) {
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
}

printSolution(dist);
}

int main() {
vector<vector<int>> graph = {
{0, 5, INF, 10},
{INF, 0, 3, INF},
{INF, INF, 0, 1},
{INF, INF, INF, 0}
};

floydWarshall(graph);
return 0;
}

OUTPUT

Shortest distances between every pair of vertices:


0 5 8 9
INF 0 3 4
INF INF 0 1
INF INF INF 0
PROGRAM-26
Write a program for the implementation of Dynamic Programing:-Longest Common
Subsequence.

#include <iostream>
#include <vector>
#include <string>
using namespace std;

int longestCommonSubsequence(string s1, string s2) {


int m = s1.length();
int n = s2.length();
vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (s1[i - 1] == s2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[m][n];
}

int main() {
string s1 = "AGGTAB";
string s2 = "GXTXAYB";
int lcs_length = longestCommonSubsequence(s1, s2);
cout << "Length of Longest Common Subsequence: " << lcs_length <<
endl;

return 0;
}

OUTPUT

Length of Longest Common Subsequence: 4


PROGRAM-27
Write a program for the implementation of Dynamic Programing:-Traveling Salesman.

#include <iostream>
using namespace std;
int graph[4][4] = {
{0, 8, 15, 20},
{10, 0, 35, 2},
{15, 20, 0, 30},
{20, 25, 3, 0}
};

int visited[4];
int min_cost = INT_MAX;

void tsp(int current_city, int cost, int count) {


if (count == 4 && graph[current_city][0]) {
if (cost + graph[current_city][0] < min_cost) {
min_cost = cost + graph[current_city][0];
}
return;
}

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


if (!visited[i] && graph[current_city][i]) {
visited[i] = 1;
tsp(i, cost + graph[current_city][i], count + 1);
visited[i] = 0;
}
}
}

int main() {
for (int i = 0; i < 4; i++) {
visited[i] = 0;
}
visited[0] = 1;

tsp(0, 0, 1);

printf("Minimum cost: %d\n", min_cost);

return 0;
}

OUTPUT

Minimum cost: 28
PROGRAM-28
Write a program for the implementation of Backtracking:-n-queen.

#include<iostream>
#include<vector>
using namespace std;
bool safe(int row,int col,vector<string>&board,int n){
for(int i =0;i<=row;i++){
if(board[i][col]=='Q'){
return false;
}
}
for(int i = row-1,j=col-1;i>=0&&j>=0;i--,j--){
if(board[i][j]=='Q')
return false;
}
for(int i = row-1,j=col+1;i>=0&&j<n;i--,j++){
if(board[i][j]=='Q')
return false;
}
return true;
}
void solve(int row,vector<string>&board,vector<vector<string>>&ans,int n){
if(row==n){ans.push_back(board);
return;}
for(int col=0;col<n;col++){
if(safe(row,col,board,n)){
board[row][col]='Q';
solve(row+1,board,ans,n);
board[row][col]='.';
}
}
}
vector<vector<string>>solveNqueen(int n){
vector<vector<string>>ans;
vector<string>board(n,string(n,'.'));
solve(0,board,ans,n);
return ans;
}
int main(){
int n;
cout << "Enter the value of N: ";
cin >> n;
vector<vector<string>> solutions = solveNqueen(n);
cout << "Total solutions: " << solutions.size() << endl;
for (auto &sol : solutions) {
for (string &row : sol)
cout << row << endl;
cout << endl;}
return 0;}
OUTPUT

Enter the value of N: 4


Total solutions: 2
.Q..
...Q
Q...
..Q.

..Q.
Q...
...Q
.Q..
PROGRAM-29
Write a program for the implementation of Backtracking:-Graph Coloring.

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

#define V 5

void printColors(vector<int>& color, int n) {


cout << "Vertex -> Color\n";
for (int i = 0; i < n; i++)
cout << " " << i << " -> " << color[i] << endl;

int maxColor = 0;
for (int i = 0; i < n; i++) {
if (color[i] > maxColor)
maxColor = color[i];
}
cout << "Total colors used: " << maxColor << endl;
}

void greedyColoring(int graph[V][V]) {


vector<int> color(V);
color[0] = 1;

for (int i = 1; i < V; i++)


color[i] = 0;

vector<bool> available(V + 1, true);


for (int u = 1; u < V; u++) {
fill(available.begin(), available.end(), true);
for (int i = 0; i < V; i++) {
if (graph[u][i] && color[i] != 0)
available[color[i]] = false;
}

for (int c = 1; c <= V; c++) {


if (available[c]) {
color[u] = c;
break;
}
}
}

printColors(color, V);
}

int main() {
int graph[V][V] = {
{0, 1, 1, 1, 0},
{1, 0, 1, 0, 1},
{1, 1, 0, 1, 1},
{1, 0, 1, 0, 0},
{0, 1, 1, 0, 0}
};

greedyColoring(graph);
return 0;
}

OUTPUT

Vertex -> Color


0 -> 1
1 -> 2
2 -> 3
3 -> 2
4 -> 1
Total colors used: 3
PROGRAM-30
Write a program for the implementation of Backtracking:-Hamiltonian Cycle.

#include <iostream>
#include <vector>
using namespace std;

#define V 5

void printSolution(vector<int>& path) {


cout << "Hamiltonian Cycle Exists:\nCycle: ";
for (int i = 0; i < V; i++) {
cout << path[i] << " ";
}
cout << path[0] << endl;
}

bool isSafe(int v, vector<vector<bool>>& graph, vector<int>& path, int pos) {


if (graph[path[pos - 1]][v] == 0)
return false;
for (int i = 0; i < pos; i++)
if (path[i] == v)
return false;
return true;
}

bool hamCycleUtil(vector<vector<bool>>& graph, vector<int>& path, int pos)


{
if (pos == V) {
if (graph[path[pos - 1]][path[0]] == 1)
return true;
else
return false;
}
for (int v = 1; v < V; v++) {
if (isSafe(v, graph, path, pos)) {
path[pos] = v;
if (hamCycleUtil(graph, path, pos + 1) == true)
return true;
path[pos] = -1;
}
}
return false;
}

bool hamCycle(vector<vector<bool>>& graph) {


vector<int> path(V, -1);
path[0] = 0;
if (hamCycleUtil(graph, path, 1) == false) {
cout << "No Hamiltonian Cycle exists.\n";
return false;
}
printSolution(path);
return true;
}

int main() {
vector<vector<bool>> graph = {
{0, 1, 0, 1, 0},
{1, 0, 1, 1, 1},
{0, 1, 0, 0, 1},
{1, 1, 0, 0, 1},
{0, 1, 1, 1, 0}
};

hamCycle(graph);
return 0;
}

OUTPUT

Hamiltonian Cycle Exists:


Cycle: 0 1 2 4 3 0

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