You are on page 1of 25

BRANCH: CSE

LAB MANUAL SEM-IV

Analysis & Design of


Algorithms

Course Details

Name of the Programme : Under Graduate

Branch : CSE

Semester : 4th

Name of Subject : Analysis & Design of Algorithms

Subject Code : CS-4004

Category of Course : Compulsory


BRANCH: CSE

LIST OF EXPERIMENTS SEM-IV

Analysis & Design of


Algorithms

Sr. No. of Practical


No Periods
.
1 2 Write a program for Iterative and Recursive Binary Search in a given
array.
2 2 Write a program for Insertion Sort.
3 2 Write a program for Merge Sort.
4 2 Write a program for Quick Sort.
5 2 Write a program for Heap Sort.
6 2 Write a program for solving greedy knapsack problem on a given set of
items.
7 2 Write a program for sequencing of jobs given deadlines and profits for
each job using greedy approach.

8 Write a program to find shortest path on a graph using dijkstra’s


algorithm.

9 2 Write a program for Floyd-Warshall’s algorithm.

10 2 Write a program for implementing N-Queens problem.

11 2 Write a program for graph traversals


• BFS
• DFS

12 2 Write a program to create binary tree and also perform following tree
traversals.
• In-order
• Pre-Order
• Post-Order
13 1 Write a program for 15 puzzle problem.

Signature of Head Signature of Faculty


Date: Date:
PROGRAM 1: Write a program for Iterative and Recursive Binary Search in
a given array.

#include<stdio.h>
#include<conio.h>
#define SIZE 10
int n;
void main()
{ int A[SIZE],KEY,i,flag,low,high;
int BinSearch(int A[SIZE],int KEY,int low,int high);
clrscr();
printf("\n How Many elements in an array?");
scanf("%d",&n);
printf("\n Enter The Elements");
for(i=0;i<n;i++)
scanf("%d",&A[i]);
printf("\n Enter the element which is to be searched");
scanf("%d",&KEY);
low=0;
high=n-1;
flag=BinSearch(A,KEY,low,high);
printf("\n The element is at A[%d] location",flag);
getch();}
int BinSearch(int A[SIZE],int KEY,int low,int high)
{ int m;
m=(low+high)/2; //mid of the array is obtained
if(KEY==A[m])
return m;
else if(KEY<A[m])
BinSearch(A,KEY,low,m-1);//search the left sub list
else
BinSearch(A,KEY,m+1,high);//search the right sub list
}
PROGRAM 2: Write a program for Insertion Sort.

#include<stdio.h>
#include<conio.h>
int main()
{int a[100],n,i;
int j,temp; //Iterate start from first element
printf("Enter the number of element you want to Sort : ");
scanf("%d",&n);
printf("Enter Elements in the list : ");
for(i = 0; i < n; i++)
{ scanf("%d",&a[i]); }
}
for(i=1; i<n; i++) //staring from the second element.
{ temp= a[i]; //selecting the next element to be inserted.
for(j = i-1; j>=0;j--)//inserting the element in previously sorted sub array
{
If(a[j]>temp)// check whether second element is greater than
{ first element
a[j+1] = a[j]; //insert first element at second
}
a[j+1] = temp; }//insert the element at identified location
}
Printf("Sorted list : "); //print sorted array
for(i = 0; i < n; i++ )
{
printf("%d\t",a[i]);
}}
PROGRAM 3: Write a program for Merge Sort.

# include<conio.h>
# include<stdio.h>
# include<stdlib.h>
int n;
void main()
{ int A[10], int i, low, high;
void MergeSort(int A[10],int low,int high);
void Display(int A[10]);
clrscr();
printf("\n\t\t Merge Sort \n"); printf("\n Enter the length of list :");
scanf("%d",&n);
printf("\n Enter list elements :");
for(i=0;i<n;i++)
scanf("%d",&A[i]);
low=0;
high=n-1;
MergeSort(A,low,high);
Display(A);
getch();
}/* This function is to split the list into sublists */
void MergeSort(int A[10],int low,int high)
{ int mid;
void Combine(int A[10],int low,int mid,int high);
if(low < high)
{ mid = (low+high)/2;//split the list at mid
MergeSort(A,low,mid);//first sublist
MergeSort(A,mid+1,high);//second sublist
Combine(A,low,mid,high);//merging of two sublists
}} /* This function is for merging the two sublists */
void Combine(int A[10],int low,int mid,int high)
{ int i,j,k;
int temp[10];
k=low;
i=low;
j=mid+1;
while(i <= mid && j <= high)
{
if(A[i]<=A[j])
{ temp[k]=A[i];
i++;
k++;
}
else
{temp[k]=A[j];
j++;
k++;
} }
While (i<=mid)
{temp[k]=A[i];
i++;
k++;
}
while(j<=high)
{temp[k]=A[j];
j++;
k++;
}
//copy the elements from temp array to A
for(k=low;k<=high;k++)
A[k]=temp[k];
}/* function to display sorted array */
void Display(int A[10])
{ int i;
printf("\n\n The Sorted Array Is ...\n");
for(i=0;i<n;i++)
printf("%d\t",A[i]);
}
PROGRAM 4: Write a program for Quick Sort.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define SIZE 10
void Quick(int A[SIZE],int,int);
int Partition(int A[SIZE],int,int);
void swap(int A[SIZE],int *,int *);
int n;
int main()
{ int i;
int A[SIZE];
clrscr();
printf("\n\t\t Quick Sort Method \n");
printf("\n Enter Total numbers to sort : ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter %dth number : ",i+1);
scanf("%d",&A[i]);
}
Quick(A,0,n-1);
printf("\n\n\t Sorted Array Is: \n");
for(i=0;i<n;i++)
printf("\t%d ",A[i]);
getch();
return 0;
}/* This function is to sort the elements in a sublist */
void Quick(int A[SIZE],int low,int high)
{ int m,i;
if(low<high)
{ m=Partition(A,low,high);//setting pivot element
Quick(A,low,m-1);//splitting of list
Quick(A,m+1,high);//splitting of list }}

/* This function is to partition a list and decide the pivot element */


int Partition(int A[SIZE],int low,int high)
{ int pivot=A[low],i=low,j=high;
while(i<=j)
{ while(A[i]<=pivot)
i++;
while(A[j]>pivot)
j--;
if(i<j)
swap(A,&i,&j);
}
swap(A,&low,&j);
return j;
} void swap(int A[SIZE],int *i,int *j)
{ int temp;
temp=A[*i];
A[*i]=A[*j];
A[*j]=temp;
}
PROGRAM 5: Write a program for Heap Sort.

#include <iostream.h>
#include <conio.h>
class heap
{int k[11],size;
public:
void getdata(void);
friend void create_heap(heap &);
friend void sort_heap(heap &);
void showdata(void);
}; void heap :: getdata(void)
{ clrscr();
cout<<"Enter the size of Array :-";
cin>>size;
cout<<"\nEnter "<<size<<" Elements\n";
for(int i=1;i<=size;i++) //Creating heap from index1 instead of index0
cin>>k[i];
} void heap :: showdata(void)
{ clrscr();
cout<<"\n\nHeap Function Output\n\n";
for(int i=1;i<=size;i++)
cout<<k[i]<<endl;
} void create_heap(heap &a)
{ int q,i,j,key;
for(q=2;q<=a.size;q++)
{ i=q;
key=a.k[i];
j=i/2;
while(i>1 && key>a.k[j])
{ a.k[i]=a.k[j];
i=j;
j=i/2;
if(j<1)
j=1;
} a.k[i]=key;
}} void sort_heap(heap &a)
{ int q,i,j,key,temp;
for(q=a.size;q>=1;q--)
{ temp=a.k[1];
a.k[1]=a.k[q];
a.k[q]=temp;
i=1;
key=a.k[i];
j=2*i;
if(j+1 < q)
{ if(a.k[j+1] > a.k[j])
j++;
} while(j<=q-1 && key<a.k[j])
{ a.k[i]=a.k[j];
i=j;
j=2*i;
if(j+1 < q)
{ if(a.k[j+1] > a.k[j])
j++;
} else break;
} a.k[i]=key;
}} void main()
{ heap o1;
o1.getdata();
create_heap(o1);
sort_heap(o1);
o1.showdata();
getch();
}
PROGRAM 6: Write a program for solving greedy knapsack problem on a
given set of items.
#include <queue>
#include <iostream>
using namespace std;
struct node
{ int level; int profit; int weight; int bound;
};
int bound(node u, int n, int W, vector<int>pVa, vector<int>wVa)
{ int j = 0, k = 0; int totweight = 0; int result = 0;
if (u.weight>= W)
    { return 0;
    } else
    { result = u.profit;
        j = u.level + 1;
totweight = u.weight;
while ((j < n) && (totweight + wVa[j] <= W))
        { totweight = totweight + wVa[j];
result = result + pVa[j];
j++;
        } k = j;
if (k < n)
        { result = result + (W - totweight) * pVa[k]/wVa[k];
        } return result; }}
int knapsack(int n, int p[], int w[], int W)
{ queue<node> Q;
node u, v;
vector<int>pV;
vector<int>wV;
Q.empty();
for (int i = 0; i < n; i++)
    { pV.push_back(p[i]);
wV.push_back(w[i]);
    } v.level = -1; v.profit = 0; v.weight = 0; int maxProfit = 0;
    //v.bound = bound(v, n, W, pV, wV);
Q.push(v);
while (!Q.empty())
    {    v = Q.front();
Q.pop();
if (v.level == -1)
        { u.level = 0;
        } else if (v.level != (n - 1))
        { u.level = v.level + 1;
        } u.weight = v.weight + w[u.level];
u.profit = v.profit + p[u.level];
u.bound = bound(u, n, W, pV, wV);
if(u.weight<= W &&u.profit>maxProfit)
        {maxProfit = u.profit;
        } if(u.bound>maxProfit)
   { Q.push(u);
        } u.weight = v.weight;
u.profit = v.profit;
u.bound = bound(u, n, W, pV, wV);
if(u.bound>maxProfit)
        {Q.push(u);} }
return maxProfit;}
int main()
{ int n ; int W,p[10],w[10];
cout<<"Enter no. of objects\n"; cin>>n;
cout<<"Enter weights and profits of objects\n";
for(int i=0;i<n;i++)
    {      cout<<"Object "<<i+1<<"\n Weight : " cin>>w[i];
            cout<<" Profit : ";   cin>>p[i]; }
cout<<"\nEnter knapsack capacity\n"; cin>>W;
cout<<"\nMaximum profit : ";
cout<< knapsack(n, p, w, W) <<endl;
return 0; }

PROGRAM 7: Write a program for sequencing of jobs given deadlines and


profits for each job using greedy approach.
#include<stdio.h>
#include<conio.h>
intjobsequence(int d[6],int j[6],int n)
{
Int q,i,r,k;d[0]=0;
 j[0]=0;
 j[1]=1;
k=1;
for(i=2;i<=n;i++)
{r=k;
while((d[j[r]]>d[i]) &&(d[j[r]]!=r))
r=r-1;
if((d[j[r]]<=d[i]) && (d[i]>r))
{
for(q=k;q>=r+1;q--)
{
 j[q+1]=j[q];

j[r+1]=i;k=k+1;}}
return k;}
PROGRAM 8: Write a program to find shortest path on a graph using
dijkstra’s algorithm.
include<iostream>
#include<conio.h>
#include<stdio.h>
using namespace std;
int shortest(int ,int);
int cost[10][10],dist[20],i,j,n,k,m,S[20],v,totcost,path[20],p;
main()
{
int c;
cout <<"enter no of vertices";
cin >> n;
cout <<"enter no of edges";
cin >>m;
cout <<"\nenter\nEDGE Cost\n";
for(k=1;k<=m;k++)
{
cin >> i >> j >>c;
cost[i][j]=c;
}
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(cost[i][j]==0)
cost[i][j]=31999;
cout <<"enter initial vertex";
cin >>v;
cout << v<<"\n";
shortest(v,n);
}
 
int shortest(int v,int n)
{
int min;
for(i=1;i<=n;i++)
{
S[i]=0;
dist[i]=cost[v][i];
}
path[++p]=v;
S[v]=1;
dist[v]=0;
for(i=2;i<=n-1;i++)
{
k=-1;
min=31999;
for(j=1;j<=n;j++)
{
if(dist[j]<min && S[j]!=1)
{
min=dist[j];
k=j;
}
}
if(cost[v][k]<=dist[k])
p=1;
path[++p]=k;
for(j=1;j<=p;j++)
cout<<path[j];
cout <<"\n";
//cout <<k;
S[k]=1;
for(j=1;j<=n;j++)
if(cost[k][j]!=31999 && dist[j]>=dist[k]+cost[k][j] && S[j]!=1)
dist[j]=dist[k]+cost[k][j];
}
}

PROGRAM 9: Write a program for Floyd-Warshall’s algorithm.


#include <iostream>
#include <conio.h>
using namespace std;
void floyds(int b[][7])
{ int i, j, k;
for (k = 0; k < 7; k++)
{ for (i = 0; i < 7; i++)
{ for (j = 0; j < 7; j++)
{ if ((b[i][k] * b[k][j] != 0) && (i != j))
{ if ((b[i][k] + b[k][j] < b[i][j]) || (b[i][j] == 0))
{ b[i][j] = b[i][k] + b[k][j];
} } } } }
for (i = 0; i < 7; i++)
{ cout<<"\nMinimum Cost With Respect to Node:"<<i<<endl;
for (j = 0; j < 7; j++)
{ cout<<b[i][j]<<"\t";
}}
int main()
{ int b[7][7];
cout<<"ENTER VALUES OF ADJACENCY MATRIX\n\n";
for (int i = 0; i < 7; i++)
{ cout<<"enter values for "<<(i+1)<<" row"<<endl;
for (int j = 0; j < 7; j++)
{ cin>>b[i][j];
} }
floyds(b);
getch();
}
PROGRAM 10: Write a program for implementing N-Queens problem.
#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<process.h>
int board[20]; int count;
void main()
{ int n,i,j;
void Queen(int row,int n);
clrscr();
printf("\n\t Program for n-Queen's Using Backtracking");
printf("\nEnter Number of Queen's");
scanf("%d",&n);
Queen(1,n);//trace using backtrack
getch();
}/* This function is for printing the solution to n-queen's problem */
void print_board(int n)
{ int i,j;
printf("\n\nSolution %d : \n\n",++count); //number of solution
for(i=1;i<=n;i++)
{printf("\t%d",i);
}for(i=1;i<=n;i++)
{ printf("\n\n%d",i);
for(j=1;j<=n;j++)// for board
{ if(board[i]==j)
printf("\tQ");//Queen at i,j position
else
printf("\t–");// empty slot
}}
printf("\n Press any key to continue...");
getch();}
/* This function is for checking for the conflicts. If there is no conflict for the desired
position it returns 1 otherwise it returns 0 */

int place(int row,int column)


{ int i;
for(i=1;i<=row-1;i++)
{ //checking for column and diagonal conflicts
if(board[i] == column)
return 0;
else
if(abs(board[i] - column) == abs(i - row))
return 0;
}
//no conflicts hence Queen can be placed
return 1;
}

/* By this function we try the next free slot and 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 conflict so place queen
if(row==n)//dead end
print_board(n);
//printing the board configuration
else //try next queen with next position
Queen(row+1,n);
}
}
}

PROGRAM 11: Write a program for graph traversals BFS & DFS

BFS
#include<iostream>
#include <list>
using namespace std;
// This class represents a directed graph using
// adjacency list representation
class Graph
{ int V; // No. of vertices
// Pointer to an array containing adjacency
// lists
list<int> *adj;
public:
Graph(int V); // Constructor
// function to add an edge to graph
void addEdge(int v, int w);
// prints BFS traversal from a given source s
void BFS(int s);
};
Graph::Graph(int V)
{ this->V = V;
adj = new list<int>[V];
}
void Graph::addEdge(int v, int w)
{ adj[v].push_back(w); // Add w to v’s list.
}
void Graph::BFS(int s)
{ // Mark all the vertices as not visited
bool *visited = new bool[V];
for(int i = 0; i < V; i++)
visited[i] = false;

// Create a queue for BFS


list<int> queue;
// Mark the current node as visited and enqueue it
visited[s] = true;
queue.push_back(s);
// 'i' will be used to get all adjacent
// vertices of a vertex
list<int>::iterator i;
while(!queue.empty())
{ // Dequeue a vertex from queue and print it
s = queue.front();
cout << s << " ";
queue.pop_front();
// Get all adjacent vertices of the dequeued
// vertex s. If a adjacent has not been visited,
// then mark it visited and enqueue it
for (i = adj[s].begin(); i != adj[s].end(); ++i)
{ if (!visited[*i])
{ visited[*i] = true;
queue.push_back(*i);
} } } }
// Driver program to test methods of graph class
int main()
{ // Create a graph given in the above diagram
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
cout << "Following is Breadth First Traversal "<< "(starting from vertex 2) \n";
g.BFS(2);
return 0;}
DFS
#include<iostream>
#include<list>
using namespace std;
// Graph class represents a directed graph
// using adjacency list representation
class Graph
{ int V; // No. of vertices
// Pointer to an array containing
// adjacency lists
list<int> *adj;
// A recursive function used by DFS
void DFSUtil(int v, bool visited[]);
public:
Graph(int V); // Constructor
// function to add an edge to graph
void addEdge(int v, int w);
// DFS traversal of the vertices
// reachable from v
void DFS(int v);
};
Graph::Graph(int V)
{ this->V = V;
adj = new list<int>[V];
}
void Graph::addEdge(int v, int w)
{ adj[v].push_back(w); // Add w to v’s list.
}
void Graph::DFSUtil(int v, bool visited[])
{ // Mark the current node as visited and
// print it
visited[v] = true;
cout << v << " "; // Recur for all the vertices adjacent
// to this vertex
list<int>::iterator i;
for (i = adj[v].begin(); i != adj[v].end(); ++i)
if (!visited[*i])
DFSUtil(*i, visited);
}
// DFS traversal of the vertices reachable from v.
// It uses recursive DFSUtil()
void Graph::DFS(int v)
{
// Mark all the vertices as not visited
bool *visited = new bool[V];
for (int i = 0; i < V; i++)
visited[i] = false;

// Call the recursive helper function


// to print DFS traversal
DFSUtil(v, visited);
}

int main()
{
// Create a graph given in the above diagram
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
cout << "Following is Depth First Traversal" " (starting from vertex 2) \n";
g.DFS(2);
return 0;
}
PROGRAM 12: Write a program to create binary tree and also perform
following tree traversals.
In-order, Pre-Order and Post-Order.
#include <stdio.h>
#include <stdlib.h>
/* A binary tree node has data, pointer to left child and a pointer to right child */
struct node
{ int data; struct node* left; struct node* right;
};
/* Helper function that allocates a new node with the given data and NULL left and
right pointers. */
struct node* newNode(int data)
{ struct node* node = (struct node*) malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
/* Given a binary tree, print its nodes according to the "bottom-up" postorder traversal.
*/ void printPostorder(struct node* node)
{ if (node == NULL)
return;
// first recur on left subtree
printPostorder(node->left);
// then recur on right subtree
printPostorder(node->right);
// now deal with the node
printf("%d ", node->data);
} /* Given a binary tree, print its nodes in inorder*/
void printInorder(struct node* node)
{ if (node == NULL)
return;
/* first recur on left child */
printInorder(node->left);

/* then print the data of node */


printf("%d ", node->data);
/* now recur on right child */
printInorder(node->right);
}
/* Given a binary tree, print its nodes in preorder*/
void printPreorder(struct node* node)
{
if (node == NULL)
return;
/* first print data of node */
printf("%d ", node->data);
/* then recur on left sutree */
printPreorder(node->left);
/* now recur on right subtree */
printPreorder(node->right);
}
/* Driver program to test above functions*/
int main()
{ struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
printf("\nPreorder traversal of binary tree is \n");
printPreorder(root);
printf("\nInorder traversal of binary tree is \n");
printInorder(root);
printf("\nPostorder traversal of binary tree is \n");
printPostorder(root);
getchar();
return 0;
}

You might also like