0% found this document useful (0 votes)
21 views23 pages

Ada Lab

The document contains 18 programming problems related to algorithms and data structures. Some of the problems involve sorting algorithms like selection sort, merge sort, and quick sort. Other problems involve graph algorithms like depth-first search and breadth-first search. Additional algorithm categories include dynamic programming, greedy algorithms, and minimum spanning tree algorithms. The document provides sample code for selection sort, travelling salesman problem, 0/1 knapsack problem, and graph search algorithms.

Uploaded by

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

Ada Lab

The document contains 18 programming problems related to algorithms and data structures. Some of the problems involve sorting algorithms like selection sort, merge sort, and quick sort. Other problems involve graph algorithms like depth-first search and breadth-first search. Additional algorithm categories include dynamic programming, greedy algorithms, and minimum spanning tree algorithms. The document provides sample code for selection sort, travelling salesman problem, 0/1 knapsack problem, and graph search algorithms.

Uploaded by

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

1. Write a program to sort a list of N elements using Selection Sort Technique.

2. Write a program to perform Travelling Salesman Problem.


3. Write program to implement Dynamic Programming algorithm for the 0/1 Knapsack
problem. 4. Write a program to perform Knapsack Problem using Greedy Solution.
5. Write program to implement the DFS and BFS algorithm for a graph.
6. Write a program to find minimum and maximum value in an array using divide and
conquer. 7. Write a test program to implement Divide and Conquer Strategy. Eg:
Quick sort algorithm for sorting list of integers in ascending order.
8. Write a program to implement Merge sort algorithm for sorting a list of integers
in ascending order.
9. Sort a given set of n integer elements using Merge Sort method and compute its
time complexity. Run the program for varied values of n> 5000, and record the time
taken to sort.
10. Sort a given set of n integer elements using Quick Sort method and compute its
time complexity. Run the program for varied values of n> 5000 and record the time
taken to sort.
11. Write C program that accepts the vertices and edges for a graph and stores it
as an adjacency matrix.
12. Implement function to print In-Degree, Out-Degree and to display that adjacency
matrix.
13. Write program to implement backtracking algorithm for solving problems like N
queens .
14. Write a program to implement the backtracking algorithm for the sum of subsets
problem.
15. Write program to implement greedy algorithm for job sequencing with deadlines.
16. Write program to implement Dynamic Programming algorithm for the Optimal Binary
Search Tree Problem.
17. Write a program that implements Prim's algorithm to generate minimum cost
spanning Tree.
18. Write a program that implements Kruskal's algorithm to generate minimum cost
spanning Tree.l
1. Write a program to sort a list of N elements using selection sort technique.
#include<stdio.h>
#include<conio.h>
void main()
{
int i,t,j,k,n,a[10];
clrscr();
printf("enter the value of n:");
scanf("%d",&n);
printf("enter the array elements:");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
for(i=1;i<=n;i++)
{
j=i;
for(k=i+1;k<=n;k++)
{
if(a[k]<a[j])
{
j=k;
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
printf("sorted array is \n");
for(i=1;i<=n;i++)
printf("%d\t",a[i]);
getch();
}

OUTPUT:

enter the value of n:4


enter the array elements:5 7 1 9
sorted array is
1 5 7 9

2. Write a program to perform Travelling Salesman Problem

#include <stdio.h>
int matrix[25][25], visited_cities[10], limit, cost = 0;
int tsp(int c)
{
int count, nearest_city = 999;
int minimum = 999, temp;
for(count = 0; count < limit; count++)
{
if((matrix[c][count] != 0) && (visited_cities[count] == 0))
{
if(matrix[c][count] < minimum)
{
minimum = matrix[count][0] + matrix[c][count];
}
temp = matrix[c][count];
nearest_city = count;
}
}
if(minimum != 999)
{
cost = cost + temp;
}
return nearest_city;
}
void minimum_cost(int city)
{
int nearest_city;
visited_cities[city] = 1;
printf("%d ", city + 1);
nearest_city = tsp(city);
if(nearest_city == 999)
{
nearest_city = 0;
printf("%d", nearest_city + 1);
cost = cost + matrix[city][nearest_city];
return;
}
minimum_cost(nearest_city);
}
int main()
{
int i, j;
clrscr();
printf("Enter Total Number of Cities:\t");
scanf("%d", &limit);
printf("\nEnter Cost Matrix\n");
for(i = 0; i < limit; i++)
{
printf("\nEnter %d Elements in Row[%d]\n", limit, i + 1);
for(j = 0; j < limit; j++)
{
scanf("%d", &matrix[i][j]);
}
visited_cities[i] = 0;
}
printf("\nEntered Cost Matrix\n");
for(i = 0; i < limit; i++)
{
printf("\n");
for(j = 0; j < limit; j++)
{
printf("%d ", matrix[i][j]);
}
}
printf("\n\nPath:\t");
minimum_cost(0);
printf("\n\nMinimum Cost: \t");
printf("%d\n", cost);
return 0;
}

OUTPUT:

Enter 3 Elements in Row[1]


30
40
50

Enter 3 Elements in Row[2]


10
60
70

Enter 3 Elements in Row[3]


70
30
20

Entered Cost Matrix

30 40 50
10 60 70
70 30 20

Path: 1 3 2 1
Minimum Cost: 90

3. Write program to implement Dynamic Programming algorithm for the 0/1 Knapsack
problem.

#include<stdio.h>
#include<conio.h>
void main()
{
int v[20],w[20],i,j,n,W;
void knapsack(int [],int [],int,int);
clrscr();
printf("Number of objects:");
scanf("%d",&n);
printf("Capacity of knapsack:");
scanf("%d",&W);
for(i=1;i<=n;i++)
{
printf("Enter Weight and value of object %d =",i);
scanf("%d",&w[i]);
scanf("%d",&v[i]);
}
knapsack(v,w,n,W);
getch();
}
void knapsack(int v[],int w[],int n,int W)
{
int k[20][20],i,j;
for(i=0;i<=n;i++)
{
for(j=0;j<=W;j++)
{
if(i==0 || j==0)
{
k[i][j]=0;
}
else if(j<w[i])
{
k[i][j]=k[i-1][j];
}
else
{
if(k[i-1][j]>k[i-1][j-w[i]]+v[i])
{
k[i][j]=k[i-1][j];
}
else
{
k[i][j]=k[i-1][j-w[i]]+v[i];
}
}
}
}
for(i=0;i<=n;i++)
{
for(j=0;j<=W;j++)
{
printf(" %d",k[i][j]);
}
printf("\n");
}
printf("___________________________");
printf("\n Maximum possible profit=%d",k[n][W]);
printf("\n___________________________");
getch();
}

OUTPUT:

Number of objects:5
Capacity of knapsack:11
Enter Weight and value of object 1 =1 1
Enter Weight and value of object 2 =2 6
Enter Weight and value of object 3 =5 18
Enter Weight and value of object 4 =6 22
Enter Weight and value of object 5 =7 28
0 0 0 0 0 0 0 0 0 0 0 0
0 1 1 1 1 1 1 1 1 1 1 1
0 1 6 7 7 7 7 7 7 7 7 7
0 1 6 7 7 18 19 24 25 25 25 25
0 1 6 7 7 18 22 24 28 29 29 40
0 1 6 7 7 18 22 28 29 34 35 40
___________________________
Maximum possible profit=40
___________________________

4. Write a program to perform Knapsack Problem using Greedy Solution.

#include<stdio.h>
int main()
{
float weight[50],profit[50],ratio[50],totalvalue,temp,capacity,amount;
int n,i,j;
clrscr();
printf("Enter the number of items:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter weight and profit for item[%d]:\n",i);
scanf("%f%f",&weight[i],&profit[i]);
}
printf("Enter the capacity of knapsack:\n");
scanf("%f",&capacity);
for(i=0;i<n;i++)
ratio[i]=profit[i]/weight[i];
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
if(ratio[i]<ratio[j])
{
temp=ratio[j];
ratio[j]=ratio[i];
ratio[i]=temp;
temp=weight[j];
weight[j]=weight[i];
weight[i]=temp;
temp=profit[j];
profit[j]=profit[i];
profit[i]=temp;
}
printf("Knapsack problem using greedy alogithum:\n");
for(i=0;i<n;i++)
{
if(weight[i]>capacity)
break;
else
{
totalvalue=totalvalue+profit[i];
capacity=capacity-weight[i];
}
}
if(i<n)
totalvalue=totalvalue+(ratio[i]*capacity);
printf("\n the profit value is:%f \n",totalvalue);
return 0;
}

OUTPUT:

Enter the number of items:3


Enter weight and profit for item[0]:
1
10
Enter weight and profit for item[1]:
2
20
Enter weight and profit for item[2]:
3
30
Enter the capacity of knapsack:
5
Knapsack problem using greedy alogithum:

the profit value is:50.000000

5. Write program to implement the DFS and BFS algorithm for a graph.
a. Binary First Search.
#include <stdio.h>
#include <stdlib.h>
#define MAX 5
struct Vertex {
char label;
int visited;
};

int queue[MAX];
int rear = -1;
int front = 0;
int queueItemCount = 0;

struct Vertex* lstVertices[MAX];

int adjMatrix[MAX][MAX];
int vertexCount = 0;

void insert(int data) {


queue[++rear] = data;
queueItemCount++;
}
int removeData() {
queueItemCount--;
return queue[front++];
}
int isQueueEmpty() {
return queueItemCount == 0;
}

void addVertex(char label) {


struct Vertex* vertex = (struct Vertex*) malloc(sizeof(struct Vertex));
vertex->label = label;
vertex->visited = 0;
lstVertices[vertexCount++] = vertex;
}

void addEdge(int start,int end) {


adjMatrix[start][end] = 1;
adjMatrix[end][start] = 1;
}

void displayVertex(int vertexIndex) {


printf("%c ",lstVertices[vertexIndex]->label);
}

int getAdjUnvisitedVertex(int vertexIndex) {


int i;

for(i = 0; i<vertexCount; i++) {


if(adjMatrix[vertexIndex][i] == 1 && lstVertices[i]->visited == 0)
return i;
}
return -1;
}
void breadthFirstSearch() {
int i,unvisitedVertex;

lstVertices[0]->visited = 1;

displayVertex(0);

insert(0);

while(!isQueueEmpty()) {

int tempVertex = removeData();

while((unvisitedVertex = getAdjUnvisitedVertex(tempVertex)) != -1) {


lstVertices[unvisitedVertex]->visited = 1;
displayVertex(unvisitedVertex);
insert(unvisitedVertex);
}
}
for(i = 0;i<vertexCount;i++) {
lstVertices[i]->visited = 0;
}
}
int main() {
int i, j;
clrscr();

for(i = 0; i<MAX; i++) {


for(j = 0; j<MAX; j++)
adjMatrix[i][j] = 0;
}
addVertex('S');
addVertex('A');
addVertex('B');
addVertex('C');
addVertex('D');
addEdge(0, 1);
addEdge(0, 2);
addEdge(0, 3);
addEdge(1, 4);
addEdge(2, 4);
addEdge(3, 4);
printf("\nBreadth First Search: ");
breadthFirstSearch();
return 0;
}

OUTPUT:
Breadth First Search: S A B C D

b. Depth First Search.


#include <stdio.h>
#include <stdlib.h>
#define MAX 5
struct Vertex {
char label;
int visited;
};
int stack[MAX];
int top = -1;
struct Vertex* lstVertices[MAX];
int adjMatrix[MAX][MAX];
int vertexCount = 0;
void push(int item) {
stack[++top] = item;
}
int pop() {
return stack[top--];
}
int peek() {
return stack[top];
}
int isStackEmpty() {
return top == -1;
}

void addVertex(char label) {


struct Vertex* vertex = (struct Vertex*) malloc(sizeof(struct Vertex));
vertex->label = label;
vertex->visited = 0;
lstVertices[vertexCount++] = vertex;
}

void addEdge(int start,int end) {


adjMatrix[start][end] = 1;
adjMatrix[end][start] = 1;
}

void displayVertex(int vertexIndex) {


printf("%c ",lstVertices[vertexIndex]->label);
}

int getAdjUnvisitedVertex(int vertexIndex) {


int i;
for(i = 0; i < vertexCount; i++) {
if(adjMatrix[vertexIndex][i] == 1 && lstVertices[i]->visited == 0) {
return i;
}
}
return -1;
}
void depthFirstSearch() {
int i;

lstVertices[0]->visited = 1;

displayVertex(0);

push(0);
while(!isStackEmpty()) {

int unvisitedVertex = getAdjUnvisitedVertex(peek());

if(unvisitedVertex == -1) {
pop();
} else {
lstVertices[unvisitedVertex]->visited = 1;
displayVertex(unvisitedVertex);
push(unvisitedVertex);
}
}
for(i = 0;i < vertexCount;i++) {
lstVertices[i]->visited = 0;
}
}
int main()
{
int i, j;
clrscr();

for(i = 0; i < MAX; i++) {


for(j = 0; j < MAX; j++)
adjMatrix[i][j] = 0;
}
addVertex('S');
addVertex('A');
addVertex('B');
addVertex('C');
addVertex('D');
addEdge(0, 1);
addEdge(0, 2);
addEdge(0, 3);
addEdge(1, 4);
addEdge(2, 4);
addEdge(3, 4);

printf("Depth First Search: ");


depthFirstSearch();
return 0;
}

OUTPUT:

Depth First Search: S A D B C

6.Write a program to find minimum and maximum value in an array using divide and
conquer.

#include<stdio.h>
int max,min;
int a[100];
void maxmin(int i,int j)
{
int max1,min1,mid;
if(i==j)
{
max=min=a[i];
}
else
{
if(i==j-1)
{
if(a[i]<a[j])
{
max=a[j];
min=a[i];
}
else
{
max=a[i];
min=a[j];
}
}
else
{
mid=(i+j)/2;
maxmin(i,mid);
max1=max;
min1=min;
maxmin(mid+1,j);
if(max<max1)
max=max1;
if(min>min1)
min=min1;
}
}
}
int main()
{
int i,num;
clrscr();
printf(" \n enter the total number of numbers:");
scanf("%d",&num);
printf("enter the number\n");
for(i=1;i<=num;i++)
scanf("%d",&a[i]);
max=a[0];
min=a[0];
maxmin(1,num);
printf("minimum element in array:%d\n",min);
printf("maximum element in array:%d\n",max);
return 0;
}

OUTPUT:

enter the total number of numbers:4


enter the number
8
2
9
1
minimum element in array:1
maximum element in array:9

7. Write a test program to implement Divide and Conquer Strategy. Eg: Quick sort
algorithm for sorting list of integers in ascending order.

#include<stdio.h>
#include<conio.h>
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],j;
int i=(low-1);
for(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 main()
{
int i,arr[]={10,7,8,9,1,5};
int n=sizeof(arr)/sizeof(arr[0]);
clrscr();
printf(" array elements are\n");
for(i=1;i<=n;i++)
printf("%d\n",arr[i]);
quicksort(arr,0,n-1);
printf(" sorted array \n");
for(i=1;i<n;i++)
printf("%d\t",arr[i]);
getch();
}

OUTPUT:
array elements are
7
8
9
1
5
sorted array
5 7 8 9 10

8. Write a program to implement Merge sort algorithm for sorting a list of integers
in ascending order.

#include<stdio.h>
#include<stdlib.h>
void merge(int arr[],int l,int m,int r)
{
int n1,n2,i,j,k,L[100],R[100];
n1=m-l+1;
n2=r-m;
for(i=0;i<n1;i++)
L[i]=arr[l+i];
for(j=0;j<n2;j++)
R[j]=arr[m+1+j];
i=0;
j=0;
k=l;
while(i<n1&&j<n2)
{
if(L[i]<=R[j])
{
arr[k]=L[i];
i++;
}
else
{
arr[k]=R[j];
j++;
}
k++;
}
while(i<n1)
{
arr[k]=L[i];
i++;
k++;
}
while(j<n2)
{
arr[k]=R[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 A[],int size)
{
int i;
for(i=0;i<size;i++)
printf("%d\t",A[i]);
printf("\n");
}
void main()
{
int arr[]={12,11,13,5,6,7};
int arr_size=sizeof(arr)/sizeof(arr[0]);
clrscr();
printf("given array is \n");
printArray(arr,arr_size);
mergeSort(arr,0,arr_size-1);
printf(" Sorted array \n");
printArray(arr,arr_size);
getch();
}

OUTPUT:
given array is
12 11 13 5 6 7
Sorted array
5 6 7 11 12 13
9. Sort a given set of n integer elements using Merge Sort method and compute its
time complexity. Run the program for varied values of n> 5000, and record the time
taken to sort.

#include<stdio.h>
#include<stdlib.h>
void merge(int arr[],int l,int m,int r)
{
int n1,n2,i,j,k,L[100],R[100];
n1=m-l+1;
n2=r-m;
for(i=0;i<n1;i++)
L[i]=arr[l+i];
for(j=0;j<n2;j++)
R[j]=arr[m+1+j];
i=0;
j=0;
k=l;
while(i<n1&&j<n2)
{
if(L[i]<=R[j])
{
arr[k]=L[i];
i++;
}
else
{
arr[k]=R[j];
j++;
}
k++;
}
while(i<n1)
{
arr[k]=L[i];
i++;
k++;
}
while(j<n2)
{
arr[k]=R[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 A[],int size)
{
int i;
for(i=0;i<size;i++)
printf("%d\t",A[i]);
printf("\n");
}
void main()
{
int arr[]={12,11,13,5,6,7};
int arr_size=sizeof(arr)/sizeof(arr[0]);
clrscr();
printf("given array is \n");
printArray(arr,arr_size);
mergeSort(arr,0,arr_size-1);
printf(" Sorted array \n");
printArray(arr,arr_size);
getch();
}

OUTPUT:
given array is
12 11 13 5 6 7
Sorted array
5 6 7 11 12 13

10. Sort a given set of n integer elements using Quick Sort method and compute its
time complexity. Run the program for varied values of n> 5000 and record the time
taken to sort.

#include<stdio.h>
#include<conio.h>
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],j;
int i=(low-1);
for(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 main()
{
int i,arr[]={10,7,8,9,1,5};
int n=sizeof(arr)/sizeof(arr[0]);
clrscr();
printf(" array elements are\n");
for(i=1;i<=n;i++)
printf("%d\n",arr[i]);
quicksort(arr,0,n-1);
printf(" sorted array \n");
for(i=1;i<n;i++)
printf("%d\t",arr[i]);
getch();
}

OUTPUT:
array elements are
7
8
9
1
5

sorted array
5 7 8 9 10
11. Write C program that accepts the vertices and edges for a graph and stores it
as an adjacency matrix.
#include<stdio.h>
#include<conio.h>
void main()
{
int n,e,a[10][10],i,j,node1,node2;
clrscr();
printf("enter number of nodes :\n");
scanf("%d",&n);
printf("enter number of edges :\n");
scanf("%d",&e);
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
a[i][j]=0;
printf("enter node1 and node2 information of the edges \n");
for(i=1;i<=e;i++)
{
scanf("%d%d",&node1,&node2);
a[node1][node2]=1;
a[node2][node1]=1;
}
printf("the adjacency matrix is \n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("%d\t",a[i][j]);
printf("\n");
}
getch();
}

OUTPUT:

enter number of nodes:


5
enter number of edges:
6
enter node1 and node2 information of the edges
1 2
1 3
2 3
2 4
3 4
4 5

the adjacency matrix is


0 1 1 0 0
1 0 1 1 0
1 1 0 1 0
0 1 1 0 1
0 0 0 1 0

12. Implement function to print In-Degree, Out-Degree and to display that adjacency
matrix.
#include<stdio.h>
#include<conio.h>
void main()
{
int n,e,a[10][10],i,j,node1,node2,rsum,csum;
clrscr();
printf("enter number of nodes \n:");
scanf("%d",&n);
printf("enter number of edges \n");
scanf("%d",&e);
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
a[i][j]=0;
printf("enter node1 and node2 information of the directed edges \n");
for(i=1;i<=e;i++)
{
scanf("%d%d",&node1,&node2);
a[node1][node2]=1;
}
printf("the adjacency matrix is \n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("%d\t",a[i][j]);
printf("\n");
}
for(i=1;i<=n;i++)
{
rsum=0;
csum=0;
for(j=1;j<=n;j++)
{
rsum=rsum+a[i][j];
csum=csum+a[j][i];
}

printf("Indegree of node %d is %d\n",i,csum);


printf("Outdegree of node %d is %d\n",i,rsum);
printf("\n");
}

getch();
}

OUTPUT:

enter number of nodes:


3
enter number of edges:
5
enter node1 and node2 information of the directed edges
1 2
2 3
3 2
1 3
3 1
the adjacency matrix is
0 1 1
0 0 1
1 1 0
Indegree of node 1 is 1
Outdegree of node 1 is 2

Indegree of node 2 is 2
Outdegree of node 2 is 1

Indegree of node 3 is 2
Outdegree of node 3 is 2
16. Write program to implement Dynamic Programming algorithm for the Optimal Binary
Search Tree Problem.
#include <stdio.h>
#include <limits.h>
int sum(int freq[], int i, int j);
int optCost(int freq[], int i, int j)
{
int fsum,min,r;
if (j < i)
return 0;
if (j == i)
return freq[i];
fsum = sum(freq, i, j);
min = INT_MAX;
for (r = i; r <= j; ++r)
{
int cost = optCost(freq, i, r-1) + optCost(freq, r+1, j);
if (cost < min)
min = cost;
}
return min + fsum;
}
int optimalSearchTree(int keys[], int freq[], int n)
{
return optCost(freq, 0, n-1);
}
int sum(int freq[], int i, int j)
{
int s = 0,k;
for ( k = i; k <=j; k++)
s += freq[k];
return s;
}
int main()
{
int keys[] = {10, 12, 20};
int freq[] = {34, 8, 50};
int n = sizeof(keys)/sizeof(keys[0]);
printf("Cost of Optimal BST is %d ",
optimalSearchTree(keys, freq, n));
return 0;
}

OUTPUT:

Cost of Optimal BST is 142

You might also like