Thursday, 13 November 2014
Wednesday, 12 November 2014
Depth First Search(DFS)
Aim: To implement Depth First Search non recursively
Program:
#include<stdio.h>
#include<conio.h>
int n,am[10][10],stk[10],st,v,i,j,visited[10],top=0;
void main()
{
clrscr();
printf("enter number of vertices");
scanf("%d",&n);
printf("enter adjacent matrix");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
scanf("%d",&am[i][j]);
visited[i]=0;
}
printf("enter source node:");
scanf("%d",&st);
dfs(st);
getch();
}
dfs(int st)
{
top++;
stk[top]=st;
while(top>0)
{
v=stk[top];
top--;
if(visited[v]==0)
{
visited[v]=1;
printf("-->%d",v);
}
for(i=n;i>=1;i--)
{
if(am[v][i]==1 && visited[i]==0)
{
if(instack(i)==0)
{
top++;
stk[top]=i;
}
}
}
}
}
int instack(int n)
{
for(j=1;j<=top;j++)
{rix
if(stk[j]==n)
return 1;
}
return 0;
}
Input:
The input is given in adjacency matrix as given below graph
Output:
Tuesday, 11 November 2014
Breadth First Search (BFS)
Aim: Implement Breadth first Search(BFS) non recursively itself
Program:
#include<stdio.h>
int visited[10],st,q[10],v,i,j,am[10][10],n,front=0,rear=0;
void main()
{
clrscr();
printf("enter number of vertices");
scanf("%d",&n);
printf("enter adjacent matrix");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
scanf("%d",&am[i][j]);
visited[i]=0;
}
printf("enter source node");
scanf("%d",&st);
bfs(st);
getch();
}
int bfs(int st)
{
q[rear]=st;
rear++;
while(front<rear)
{
v=q[front];
front++;
if(visited[v]==0)
{
visited[v]=1;
printf("-->%d",v);
}
for(i=1;i<=n;i++)
{
if(am[v][i]==1 && visited[i]==0)
{
if(inqueue(i)==0)
{
q[rear]=i;
rear++;
}
}
}
}
}
int inqueue(int n)
{
int j;
for(j=front;j<rear;j++)
{
if(q[j]==n)
return 1;
}
return 0;
}
input:
input is given in the adjacent matrix for the below graph
output :
Sunday, 2 November 2014
Heap sort program in c program - heap sort in data structures
Aim: To sort elements by heap order( max heap) in C program
program:
#include<stdio.h>
void main()
{
int n,a[50],i;
clrscr();
printf("enter elements to be entered");
scanf("%d",&n); printf("enter elements");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
heapsort(a,n);
printf("after sorting the elements are");
for(i=1;i<=n;i++)
printf("%d ",a[i]);
getch();
}
int heapsort(int a[],int n)
{
int t,i; heapify(a,n);
for(i=n;i>=2;i--)
{
t=a[i];
a[i]=a[1];
a[1]=t;
adjust(a,1,i-1);
}
return;
}
int heapify(int a[],int n)
{
int i; for(i=n/2;i>=1;i--)
adjust(a,i,n);
return;
}
int adjust(int a[],int i,int n)
{
int j,item,t;
j=2*i; item=a[i];
while(j<=n)
{
if(j<n && a[j]<a[j+1])
j=j+1;
if(item<=a[j])
{
t=a[j/2];
a[j/2]=a[j];
a[j]=t;
}
j=2*j;
}
}
Output:
Subscribe to:
Posts (Atom)