Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
75 views

Analysis and Design of Algorithms Practical File

The document describes an experiment to implement Dijkstra's algorithm for finding the shortest path between nodes in a graph. It defines constants, declares arrays to store the graph data, distances and predecessors. It initializes the distance of the source node to 0 and others to infinity. In a main while loop, it finds the unvisited node with the minimum distance, marks it visited, and updates distances of its unvisited neighbors if a shorter path is found through the current node.

Uploaded by

Tridon
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
75 views

Analysis and Design of Algorithms Practical File

The document describes an experiment to implement Dijkstra's algorithm for finding the shortest path between nodes in a graph. It defines constants, declares arrays to store the graph data, distances and predecessors. It initializes the distance of the source node to 0 and others to infinity. In a main while loop, it finds the unvisited node with the minimum distance, marks it visited, and updates distances of its unvisited neighbors if a shorter path is found through the current node.

Uploaded by

Tridon
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Experiment Number- 1

AIM- Implementation of Binary Search and Insertion Sort.

Code
#include<stdio.h>
#include<conio.h>

void insertionSort(int arr[], int n)


{
int i, key, j;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i-1;

/* Move elements of arr[0..i-1], that are


greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > key)
{
arr[j+1] = arr[j];
j = j-1;
}
arr[j+1] = key;
}
}

int binarySearch(int arr[], int l, int r, int x)


{
if (r >= l)
{
int mid = l + (r - l)/2;

// If the element is present at the middle itself


if (arr[mid] == x)
return mid;
// If element is smaller than mid, then
// it can only be present in left subarray
if (arr[mid] > x)
return binarySearch(arr, l, mid-1, x);
// Else the element can only be present
// in right subarray
return binarySearch(arr, mid+1, r, x);
}
return -1;
}

1
void printArray(int arr[], int n)
{
int i;
for (i=0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}

void main()
{
int arr[20], i, n, x, result;
clrscr();
printf("Enter size of array: ");
scanf("%d", &n);
printf("\nEnter data in Array: ");
for(i=0; i<n; i++)
scanf("%d", &arr[i]);

insertionSort(arr, n);
printf("\nSorted array is: \n");
printArray(arr, n);

printf("Enter element to search: ");


scanf("%d", &x);
result = binarySearch(arr, 0, n-1, x);
(result == -1)? printf("Element is not present in array") : printf("Element is present at
index %d", result+1);
getch();
}

Output

2
Experiment Number- 2
AIM- Implementation of Merge Sort and Quick Sort.

Code
#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]; // pivot
int i = (low - 1); // Index of smaller element

for (int j = low; j <= high- 1; j++)


{
// If current element is smaller than or
// equal to pivot
if (arr[j] <= pivot)
{
i++; // increment index of smaller element
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)
{
/* pi is partitioning index, arr[p] is now
at right place */
int pi = partition(arr, low, high);

// Separately sort elements before


// partition and after partition
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}

3
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;

int L[20], R[20];


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; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
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++;
}
}

4
void mergeSort(int arr[], int l, int r)
{
if (l < r)
{
int m = l+(r-l)/2;

mergeSort(arr, l, m);
mergeSort(arr, m+1, r);

merge(arr, l, m, r);
}
}

void printArray(int arr[], int size)


{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}

void main()
{
int arr[20], i, n;
clrscr();
printf("Enter size of array: ");
scanf("%d", &n);
printf("\nEnter data in array: ");
for(i=0; i<n; i++)
scanf("%d", &arr[i]);
quickSort(arr, 0, n-1);
printf("Sorted array after quick sort: \n");
printArray(arr, n);

printf("Sorted array after merge sort: \n");


mergeSort(arr, 0, n - 1);
printArray(arr, n);

getch();
}

5
Output

6
Experiment Number- 3
AIM- Implementation of Kruskal's Algorithm.

Code
#include<stdio.h>
#include<conio.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()
{
clrscr();
printf("\nKruskal's algorithm\n");
printf("\nEnter the no. of vertices:");
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("The edges of Minimum Cost Spanning Tree are\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("%d edge (%d,%d) =%d\n",ne++,a,b,min);

7
mincost +=min;
}
cost[a][b]=cost[b][a]=999;
}
printf("\nMinimum cost = %d\n",mincost);
getch();
}
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

8
Experiment Number- 4
AIM- Implementation of Prim's Algorithm.

Code
#include<stdio.h>
#include<conio.h>

int a,b,u,v,n,i,j,ne=1;
int visited[10]={0},min,mincost=0,cost[10][10];

void main()
{
clrscr();
printf("\nEnter the number of nodes:");
scanf("%d",&n);
printf("\nEnter the 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;
}
visited[1]=1;
printf("\n");
while(ne < n)
{
for(i=1,min=999;i<=n;i++)
for(j=1;j<=n;j++)
if(cost[i][j]< min)
if(visited[i]!=0)
{
min=cost[i][j];
a=u=i;
b=v=j;
}
if(visited[u]==0 || visited[v]==0)
{
printf("\n Edge %d:(%d %d) cost:%d",ne++,a,b,min);
mincost+=min;
visited[b]=1;
}
cost[a][b]=cost[b][a]=999;
}
printf("\n Minimun cost=%d",mincost);
getch();
}

9
Output

10
Experiment Number- 5
AIM- Implementation of Dijkstra's Algorithm.

Code
#include<stdio.h>
#include<conio.h>
#define INFINITY 9999
#define MAX 10

void dijikstra(int G[MAX][MAX], int n, int startnode);

void main(){
int G[MAX][MAX], i, j, n, u;
clrscr();
printf("\nEnter the no. of vertices: ");
scanf("%d", &n);
printf("\nEnter the adjacency matrix:\n");
for(i=0;i < n;i++)
for(j=0;j < n;j++)
scanf("%d", &G[i][j]);
printf("\nEnter the starting node: ");
scanf("%d", &u);
dijikstra(G,n,u);
getch();
}

void dijikstra(int G[MAX][MAX], int n, int startnode)


{
int cost[MAX][MAX], distance[MAX], pred[MAX];
int visited[MAX], count, mindistance, nextnode, i,j;
for(i=0; i<n; i++)
for(j=0;j<n;j++)
if(G[i][j]==0)
cost[i][j]=INFINITY;
else
cost[i][j]=G[i][j];

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


{
distance[i]=cost[startnode][i];
pred[i]=startnode;
visited[i]=0;
}
distance[startnode]=0;
visited[startnode]=1;
count=1;

11
while(count<n-1){
mindistance=INFINITY;
for(i=0;i < n;i++)
if(distance[i]<mindistance && !visited[i])
{
mindistance=distance[i];
nextnode=i;
}
visited[nextnode]=1;
for(i=0;i < n;i++)
if(!visited[i])
if(mindistance+cost[nextnode][i] < distance[i])
{
distance[i]=mindistance+cost[nextnode][i];
pred[i]=nextnode;
}
count++;
}

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


if(i!=startnode)
{
printf("\nDistance of %d = %d", i, distance[i]);
printf("\nPath = %d", i);
j=i;
do
{
j=pred[j];
printf(" <-%d", j);
}
while(j!=startnode);
}
}

12
Output

13
Experiment Number- 6
AIM- Implementation of Bellmanford Algorithm.

Code
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>

int Bellman_Ford(int G[20][20] , int V, int E, int edge[20][2])


{
int i,u,v,k,distance[20],parent[20],S,flag=1;
for(i=0;i<V;i++)
distance[i] = 1000 , parent[i] = -1 ;
printf("Enter source: ");
scanf("%d",&S);
distance[S-1]=0 ;
for(i=0;i<V-1;i++)
{
for(k=0;k<E;k++)
{
u = edge[k][0] , v = edge[k][1] ;
if(distance[u]+G[u][v] < distance[v])
distance[v] = distance[u] + G[u][v] , parent[v]=u ;
}
}
for(k=0;k<E;k++)
{
u = edge[k][0] , v = edge[k][1] ;
if(distance[u]+G[u][v] < distance[v])
flag = 0 ;
}
if(flag)
for(i=0;i<V;i++)
printf("Vertex %d -> cost = %d parent = %d\n",i+1,distance[i],parent[i]+1);

return flag;
}
void main()
{
int V,edge[20][2],G[20][20],i,j,k=0;
clrscr();
printf("Enter no. of vertices: ");
scanf("%d",&V);
printf("Enter graph in matrix form:\n");
for(i=0;i<V;i++)
for(j=0;j<V;j++)
{

14
scanf("%d",&G[i][j]);
if(G[i][j]!=0)
edge[k][0]=i,edge[k++][1]=j;
}

if(Bellman_Ford(G,V,k,edge))
printf("\nNo negative weight cycle\n");
else
printf("\nNegative weight cycle exists\n");
getch();
}

Output

15
Experiment Number- 7
AIM- Implementation of BFS and DFS.

Code for BFS


#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) {
for(i=1;i<=n;i++)
if(a[v][i] && !visited[i])
q[++r]=i; //discovered nodes are inserted in queue
if(f<=r) {
visited[q[f]]=1; //traversed nodes are added to visited array
bfs(q[f++]);
}
}

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

16
Code for DFS
#include<stdio.h>
#include<conio.h>

int a[20][20],reach[20],n; //a is adj. matrix, reach is array to store if node is


reachable/visited yet
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;
clrscr();
printf("\nEnter 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("\nEnter 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("\nGraph is connected");
else
printf("\nGraph is not connected");
getch();
}

17
Output for BFS

Output for DFS

18
Experiment Number- 8
AIM- Program to solve n-Queens Problem.

Code
#include<stdio.h>
#include<conio.h>
#include<math.h>

int board[20],count;

void main()
{
int n,i,j;
clrscr();
void queen(int row,int n);
printf("\n\nEnter number of Queens:");
scanf("%d",&n);
queen(1,n);
getch();
}

//function for printing the solution


void print(int n)
{
int i,j;
printf("\n\nSolution %d:\n\n",++count);
for(i=1;i<=n;++i)
printf("\t%d",i);

for(i=1;i<=n;++i)
{
printf("\n%d",i);
for(j=1;j<=n;++j) //for nxn board
{
if(board[i]==j)
printf("\tQ"); //queen at i,j position
else
printf("\t-"); //empty slot
}
}
}

/*funtion to check conflicts


If no conflict for desired postion returns 1 otherwise returns 0*/
int place(int row,int column)
{
int i;

19
for(i=1;i<=row-1;++i)
{
//checking column and digonal conflicts
if(board[i]==column)
return 0;
else
if(abs(board[i]-column)==abs(i-row))
return 0;
}
return 1; //no conflicts
}
//function to check for proper positioning of queen
void queen(int row,int n)
{
int column;
for(column=1;column<=n;++column)
{
if(place(row,column))
{
board[row]=column; //no conflicts so place queen
if(row==n) //dead end
print(n); //printing the board configuration
else //try queen with next position
queen(row+1,n);
}
}
}
Output

20
Experiment Number- 9
AIM- Program to solve 0/1-Knapsack Problem.

Code
#include<stdio.h>
#include<conio.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]);
}

void main()
{
int profit,count=0;
clrscr();
printf("\nEnter the number of items: ");
scanf("%d",&n);
printf("\nEnter the profit and weights of the items:\n");

for(i=1; i<=n; i++)


{
printf("For item number %d: ", i);
scanf("%d%d", &p[i], &w[i]);
}

printf("\nEnter the capacity: ");


scanf("%d", &cap);

21
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("Items included are:\n");
printf("S.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", profit);
getch();
}

Output

22
Experiment Number- 10
AIM- Program to solve Fractional Knapsack Problem.

Code
#include<stdio.h>
#include<conio.h>

void knapsack(int n, float weight[], float profit[], float capacity) {


float x[20], tp = 0;
int i, j, u;
u = capacity;

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


x[i] = 0.0;

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


if (weight[i] > u)
break;
else {
x[i] = 1.0;
tp = tp + profit[i];
u = u - weight[i];
}
}

if (i < n)
x[i] = u / weight[i];

tp = tp + (x[i] * profit[i]);

printf("\nThe result vector is: ");


for (i = 0; i < n; i++)
printf("%f\t", x[i]);

printf("\nMaximum profit is: %f", tp);

void main() {
float weight[20], profit[20], capacity;
int num, i, j;
float ratio[20], temp;
clrscr();
printf("\nEnter the number of objects: ");
scanf("%d", &num);

printf("\nEnter the profits and weights of each object: ");

23
for (i = 0; i < num; i++) {
scanf("%f %f", &profit[i], &weight[i]);
}

printf("\nEnter the maximum capacity of knapsack: ");


scanf("%f", &capacity);

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


ratio[i] = profit[i] / weight[i];
}

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


for (j = i + 1; j < num; 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;
}
}
}
knapsack(num, weight, profit, capacity);
getch();
}

Output

24
Experiment Number- 11
AIM- Program to count number of inversions.

Code
#include<stdio.h>
#include<conio.h>

int getInvCount(int arr[], int n)


{
int count=0;
for (int i=0; i < n-1; i++)
for (int j = i + 1; j < n; j++)
if (arr[i] > arr[j])
count++;
return count;
}

void main()
{
int arr[10], i, n;
clrscr();
printf("Enter size of array: ");
scanf("%d", &n);
printf("Enter data in array: ");
for(i=0; i<n; i++)
scanf("%d", &arr[i]);
printf("\nNumber of inversions are: %d", getInvCount(arr, n));
getch();
}

Output

25
Experiment Number- 12
AIM- Implement Selection Sort.

Code
#include<stdio.h>
#include<conio.h>

void swap(int *x, int *y)


{
int temp = *x;
*x = *y;
*y = temp;
}

void selectionSort(int arr[], int n)


{
int i, j, min_idx;
for (i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;

// Swap the found minimum element with the first element


swap(&arr[min_idx], &arr[i]);
}
}

void printArray(int arr[], int size)


{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}

void main()
{
int arr[10], i, n;
clrscr();
printf("Enter size of array: ");
scanf("%d", &n);
printf("\nEnter data in array: \n");
for(i=0; i<n; i++)
scanf("%d", &arr[i]);

26
selectionSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
getch();
}

Output

27
ALGORITHMS
1. Binary Search:

2. Insertion Sort:

3. Merge Sort

28
4. Quick Sort

5. Kruskal’s Algorithm

6. Prim’s Algorithm

29
7. Dijkstra's Algorithm

8. Bellmanford Algorithm

9. BFS

30
10. DFS

11. n-Queens Problem

31
12. 0/1-Knapsack Problem

13. Fractional Knapsack Problem

32
14. Count number of inversions

15. Selection Sort

33

You might also like