0% found this document useful (0 votes)
15 views26 pages

Important

The program implements the 0/1 knapsack problem using dynamic programming. It takes input of number of objects, profit and weight of each object and capacity of knapsack. It uses a 2D table to store solutions of sub-problems and backtracks to find which objects are included in optimal solution.

Uploaded by

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

Important

The program implements the 0/1 knapsack problem using dynamic programming. It takes input of number of objects, profit and weight of each object and capacity of knapsack. It uses a 2D table to store solutions of sub-problems and backtracks to find which objects are included in optimal solution.

Uploaded by

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

PROGRAM - 1

Write a C program to implement Quick Sort

#include<stdio.h>
void quicksort(int number[25],int first,int last){
int i, j, pivot, temp;
if(first<last){
pivot=first;
i=first;
j=last;
while(i<j){
while(number[i]<=number[pivot]&&i<last)
i++;
while(number[j]>number[pivot])
j--;
if(i<j){
temp=number[i];
number[i]=number[j];
number[j]=temp;
}
}
temp=number[pivot];
number[pivot]=number[j];
number[j]=temp;
quicksort(number,first,j-1);
quicksort(number,j+1,last);
}
}
int main(){
int i, count, number[25];
printf("How many elements are u going to enter?: ");
scanf("%d",&count);
printf("Enter %d elements: ", count);
for(i=0;i<count;i++)
scanf("%d",&number[i]);
quicksort(number,0,count-1);
printf("Order of Sorted elements: ");
for(i=0;i<count;i++)
printf(" %d",number[i]);
return 0;
}

Output:
How many elements are u going to enter?: 5
Enter 5 elements: 6 10 3 2 1
Order of Sorted elements: 1 2 3 6 10
PROGRAM – 2

Write a C program to implement Merge Sort

/*

* C Program to Perform Merge Sort using Recursion and Functions

*/

#include <stdio.h>

#include <stdlib.h>

// merge function

void Merge(int arr[], int left, int mid, int right)

int i, j, k;

int size1 = mid - left + 1;

int size2 = right - mid;

// created temporary array

int Left[size1], Right[size2];

// copying the data from arr to temporary array

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

Left[i] = arr[left + i];


for (j = 0; j < size2; j++)

Right[j] = arr[mid + 1 + j];

// merging of the array

i = 0; // intital index of first subarray

j = 0; // inital index of second subarray

k = left; // initial index of parent array

while (i < size1 && j < size2)

if (Left[i] <= Right[j])

arr[k] = Left[i];

i++;

else

arr[k] = Right[j];

j++;

k++;

// copying the elements from Left[], if any


while (i < size1)

arr[k] = Left[i];

i++;

k++;

// copying the elements from Right[], if any

while (j < size2)

arr[k] = Right[j];

j++;

k++;

//merge sort function

void Merge_Sort(int arr[], int left, int right)

if (left < right)

int mid = left + (right - left) / 2;


// recursive calling of merge_sort

Merge_Sort(arr, left, mid);

Merge_Sort(arr, mid + 1, right);

Merge(arr, left, mid, right);

// driver code

int main()

int size;

printf("Enter the size: ");

scanf("%d", &size);

int arr[size];

printf("Enter the elements of array: ");

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

scanf("%d", &arr[i]);

}
Merge_Sort(arr, 0, size - 1);

printf("The sorted array is: ");

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

printf("%d ", arr[i]);

printf("\n");

return 0;

Output:
Enter the size: 5
Enter the elements of array: 28 3 67 14 8
The sorted array is: 3 8 14 28 67
PROGRAM – 3

Write a C program to Find Minimum Cost Spanning Tree of a given undirected graph using
Kruskal’s algorithm.

#include<stdio.h>
#include<stdlib.h>
int i,j,k,a,b,u,v,n,ne=1;
int min,mincost=0,cost[9][9],parent[9];
int find(int);
int uni(int,int);

void main() {
printf("\n Implementation of Kruskal's algorithm\n\n");
printf("\nEnter the no. of vertices\n");
scanf("%d",&n);
printf("\nEnter the cost adjacency matrix\n");
for(i=1;i<=n;i++){
for(j=1;j<=n;j++) {
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
cost[i][j]=999;
}
}
printf("\nThe edges of Minimum Cost Spanning Tree are\n\n");
while(ne<n){
for(i=1,min=999;i<=n;i++) {
for(j=1;j<=n;j++){
if(cost[i][j]<min){
min=cost[i][j];
a=u=i;
b=v=j;
}
}
}
u=find(u);
v=find(v);
if(uni(u,v)){
printf("\n%d edge (%d,%d) =%d\n",ne++,a,b,min);
mincost +=min;
}
cost[a][b]=cost[b][a]=999;
}
printf("\n\tMinimum cost = %d\n",mincost);
}
int find(int i){
while(parent[i])
i=parent[i];
return i;
}

int uni(int i,int j){


if(i!=j) {
parent[j]=i;
return 1;
}
return 0;
}

Output:
PROGRAM – 4

Write a C program to find shortest paths to other vertices using Dijkstra’s algorithm, From
a given vertex in a weighted connected graph.

#include<stdio.h>
#define infinity 999

void dij(int n, int v,int cost[20][20], int dist[])


{
int i,u,count,w,flag[20],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++)
if(dist[w]<min && !flag[w]) {
min=dist[w];
u=w;
}
flag[u]=1;
count++;
for(w=1;w<=n;w++)
if((dist[u]+cost[u][w]<dist[w]) && !flag[w])
dist[w]=dist[u]+cost[u][w];
}
}
int main(){
int n,v,i,j,cost[20][20],dist[20];
printf("enter the number of nodes:");
scanf("%d",&n);
printf("\n enter the cost matrix:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++){
scanf("%d",&cost[i][j]);
if(cost[i][j] == 0)
cost[i][j]=infinity;
}
printf("\n enter the source matrix:");
scanf("%d",&v);
dij(n,v,cost,dist);
printf("\n shortest path : \n");
for(i=1;i<=n;i++)
if(i!=v)
printf("%d->%d,cost=%d\n",v,i,dist[i]);
}

Output:
PROGRAM – 5

Write a C program to perform various tree traversal algorithms for a given tree.

#include<stdio.h>
#include<stdlib.h>
typedef struct treeNode{
int data;
struct treeNode *left;
struct treeNode *right;
}treeNode;
treeNode* FindMin(treeNode *node){
if(node==NULL){/* There is no element in the tree */
return NULL;
}
if(node->left) /* Go to the left sub tree to find the min element */
return FindMin(node->left);
else
return node;
}
treeNode * insert(treeNode *node,int data){
if(node==NULL){
treeNode *temp;
temp = (treeNode *)malloc(sizeof(treeNode));
temp -> data = data;
temp -> left = temp -> right = NULL;
return temp;
}
if(data >(node->data)) {
node->right = insert(node->right,data);
}
else if(data < (node->data)){
node->left = insert(node->left,data);
}
/* Else there is nothing to do as the data is already in the tree. */
return node;
}
treeNode * deletion(treeNode *node, int data){
treeNode *temp;
if(node==NULL){
printf("Element Not Found");
}
else if(data < node->data){
node->left = deletion(node->left, data);
}
else if(data > node->data){
node->right = deletion(node->right, data);
}
else{
/* Now We can delete this node and replace with either minimum elementin the right sub tree
or maximum element in the left subtree */
if(node->right && node->left){
/* Here we will replace with minimum element in the right sub tree */
temp = FindMin(node->right);
node -> data = temp->data;
/* As we replaced it with some other node, we have to delete that node */
node -> right = deletion(node->right,temp->data);
}
else{
/* If there is only one or zero children then we can directlyremove it
from the tree and connect its parent to its child */
temp = node;
if(node->left == NULL)
node = node->right;
else if(node->right == NULL)
node = node->left;
free(temp); /* temp is longer required */
}
}
return node;
}
treeNode * search(treeNode *node, int data){
if(node==NULL){/* Element is not found */
return NULL;
}
if(data > node->data){ /* Search in the right sub tree. */
return search(node->right,data);
}
else if(data < node->data){ /* Search in the left sub tree. */
return search(node->left,data);
}
else{ /* Element Found */
return node;
}
}
void inorder(treeNode *node){
if(node!=NULL) {
inorder(node->left);
printf("%d ",node->data);
inorder(node->right);
}
else return;
}
void preorder(treeNode *node){
if(node!=NULL){
printf("%d ",node->data);
preorder(node->left);
preorder(node->right);
}
else return;
}

void postorder(treeNode *node){


if(node!=NULL){
postorder(node->left);
postorder(node->right);
printf("%d ",node->data);
}
else return;
}
void main(){
treeNode *t,*root = NULL;
int ch, elt;
do {
printf("\n ### Binary Search Tree Operations ###");
printf("\n Press 1-Creation of BST");
printf("\n 2-deleting ");
printf("\n 3-searching ");
printf("\n 4-Traverse in Inorder");
printf("\n 5-Traverse in Preorder");
printf("\n 6-Traverse in Postorder");
printf("\n 7-Exit\n");
printf("\n enter yor choice ");
scanf("%d", &ch);
switch (ch) {
case 1:
printf("enter element to be inserted");
scanf("%d", &elt);
root = insert(root, elt);
break;
case 2:
printf("enter element to be deleted");
scanf("%d",&elt);
deletion(root,elt);
break;
case 3:
printf("enter element to be search");
scanf("%d",&elt);
t=search(root,elt);
if(t==NULL)
printf("element NOT found");
break;
case 4:
printf("\n BST Traversal in INORDER \n");
inorder(root);
break;
case 5:
printf("\n BST Traversal in PREORDER \n");
preorder(root);
break;
case 6:
printf("\n BST Traversal in POSTORDER \n");
postorder(root);
break;
case 7:
printf("\n\n Terminating \n\n");
break;
default:
printf("\n\nInvalid Option !!! Try Again !! \n\n");
break;
}
} while (ch!= 7);
}

Output:
PROGRAM – 6

Write a C program to Implement 0/1 Knapsack problem using Dynamic Programming.

#include<stdio.h>
int w[10],p[10],v[10][10],n,i,j,cap,x[10]={0};

int max(int i, int j){


return ((i>j)?i:j);
}
int knap(int i,int j){
int value;
if(v[i][j]<0){
if(j<w[i])
value=knap(i-1,j);
else
value=max(knap(i-1,j),p[i]+knap(i-1,j-w[i]));
v[i][j]=value;
}
return(v[i][j]);
}
int main(){
int profit,count=0;
printf("\nEnter the number of objects ");
scanf("%d",&n);
printf("Enter the profit and weights of the elements \n ");
for(i=1;i<=n;i++){
printf("\nEnter profit and weight For object no %d :",i);
scanf("%d%d",&p[i],&w[i]);
}
printf("\nEnter the capacity ");
scanf("%d",&cap);
for(i=0;i<=n;i++)
for(j=0;j<=cap;j++)
if((i==0)||(j==0))
v[i][j]=0;
else
v[i][j]=-1;
profit=knap(n,cap);
i=n;
j=cap;
while(j!=0&&i!=0){
if(v[i][j]!=v[i-1][j]){
x[i]=1;
j=j-w[i];
i--;
}
else
i--;
}
printf("object included are \n ");
printf("Sl.no\tweight\tprofit\n");
for(i=1;i<=n;i++)
if(x[i])
printf("%d\t%d\t%d\n",++count,w[i],p[i]);
printf("Total profit = %d\n",profit);
}

Output:
PROGRAM – 7

Write a C program to Print all the nodes reachable from a given starting node in a digraph
using BFS method.

//Breadth first traversal

#include<stdio.h>
#include<conio.h>
int a[20][20],q[20],visited[20],n,i,j,f=-1,r=0;
void bfs(int v){
q[++r]=v;
visited[v]=1;
while(f<=r) {
for(i=1;i<=n;i++)
if(a[v][i] && !visited[i]){
visited[i]=1;
q[++r]=i;
}
f++;
v=q[f];
}
}

void main(){
int v;
printf("\n Enter the number of vertices:");
scanf("%d",&n);
for(i=1;i<=n;i++){
q[i]=0;
visited[i]=0;
}
printf("\n Enter graph data in matrix form:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
printf("\n Enter the starting vertex:");
scanf("%d",&v);
bfs(v);
printf("\n The node which are reachable are:\n");
for(i=1;i<=n;i++)
if(visited[i])
printf("%d\t",q[i]);
else
printf("\n Bfs is not possible");
}

Output:
PROGRAM – 8

Write a C program to Check whether a given graph is connected or not using DFS method.

//Checking 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;
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");
}

Output:
PROGRAM – 9

Write a C program to Find a subset of a given set S = {sl, s2.....sn} of n positive integers whose
sum is equal to a given positive integer d. For example, if S= {1, 2, 5, 6, 8} and d = 9 there are
two solutions {1, 2, 6} and {1, 8}.A suitable message is to be displayed if the given problem
instance doesn't have a solution.

#include<stdio.h>
#define TRUE 1
#define FALSE 0
int inc[50],w[50],sum,n;
void sumset(int ,int ,int);
int promising(int i,int wt,int total) {
return (((wt+total)>=sum)&&((wt==sum)||(wt+w[i+1]<=sum)));
}
void main() {
int i,j,n,temp,total=0;
printf("\n Enter how many numbers: ");
scanf("%d",&n);
printf("\n Enter %d numbers : ",n);
for (i=0;i<n;i++) {
scanf("%d",&w[i]);
total+=w[i];
}
printf("\n Input the sum value to create sub set: ");
scanf("%d",&sum);
for (i=0;i<=n;i++)
for (j=0;j<n-1;j++)
if(w[j]>w[j+1]) {
temp=w[j];
w[j]=w[j+1];
w[j+1]=temp;
}
printf("\n The given %d numbers in ascending order: ",n);
for (i=0;i<n;i++)
printf("%3d",w[i]);
if((total<sum))
printf("\n Subset construction is not possible");
else{
for (i=0;i<n;i++)
inc[i]=0;
printf("\n The solution using backtracking is:\n");
sumset(-1,0,total);
}
}
void sumset(int i,int wt,int total){
int j;
if(promising(i,wt,total)) {
if(wt==sum){
printf("\n{");
for (j=0;j<=i;j++)
if(inc[j])
printf("%3d",w[j]);
printf(" }\n");
} else {
inc[i+1]=TRUE;
sumset(i+1,wt+w[i+1],total-w[i+1]);
inc[i+1]=FALSE;
sumset(i+1,wt,total-w[i+1]);
}
}
}

Output:

Enter how many numbers: 5

Enter 5 numbers : 1 2 5 6 8

Input the sum value to create sub set: 9

The given 5 numbers in ascending order: 1 2 5 6 8


The solution using backtracking is:

{ 1 2 6}

{ 1 8}
PROGRAM – 10

Write a C program to Implement N Queen's problem using Back Tracking.

#include<stdio.h>
#include <stdlib.h>
#include<math.h>

int a[30],count=0;
int place(int pos){
int i;
for(i=1;i<pos;i++)
{
if((a[i]==a[pos])||((abs(a[i]-a[pos])==abs(i-pos))))
return 0;
}
return 1;
}

void print_sol(int n){


int i,j; count++;
printf("\n\nSolution #%d:\n",count);
for(i=1;i<=n;i++){
for(j=1;j<=n;j++){
if(a[i]==j)
printf("Q\t");
else
printf("*\t");
}
printf("\n");
}
}

void queen(int n){


int k=1;
a[k]=0;
while(k!=0){
a[k]=a[k]+1;
while((a[k]<=n)&&!place(k))
a[k]++;
if(a[k]<=n){
if(k==n)
print_sol(n);
else{
k++;
a[k]=0;
}
}
else
k--;
}
}

void main(){
int i,n;
printf("Enter the number of Queens\n");
scanf("%d",&n);
queen(n);
printf("\nTotal solutions=%d",count);
}

Output:
Enter the number of Queens
4

Solution #1:
* Q * *
* * * Q
Q * * *
* * Q *

Solution #2:
* * Q *
Q * * *
* * * Q
* Q * *

Total solutions=2

You might also like