Experiment No.
-01
Aim: To study about Data Structure.
In computer science, a data structure is a particular way of storing and organizing data in
a computer so that it can be used efficiently. Data structures provide a means to manage
large amounts of data efficiently, such as large databases and internet indexing services.
Usually, efficient data structures are a key to designing efficient algorithms. Some formal
design methods and programming languages emphasize data structures, rather than
algorithms, as the key organizing factor in software design. Storing and retrieving can be
carried out on data stored in both main memory and in secondary memory.
Basic principles:
Data structures are generally based on the ability of a computer to fetch and store data at
any place in its memory, specified by an address—a bit string that can be itself stored in
memory and manipulated by the program. Thus the record and array data structures are
based on computing the addresses of data items with arithmetic operations; while the
linked data structures are based on storing addresses of data items within the structure
itself. Many data structures use both principles, sometimes combined in non-trivial ways
(as in XOR linking).
The implementation of a data structure usually requires writing a set of procedures that
create and manipulate instances of that structure. The efficiency of a data structure cannot
be analyzed separately from those operations. This observation motivates the theoretical
concept of an abstract data type, a data structure that is defined indirectly by the
operations that may be performed on it, and the mathematical properties of those
operations (including their space and time cost).
List of data structures:
Stack:
In computer science, a stack is a particular kind of abstract data type or collection in
which the principal (or only) operations on the collection are the addition of an entity to
the collection, known as push and removal of an entity, known as pop.[1] The relation
between the push and pop operations is such that the stack is a Last-In-First-Out (LIFO)
data structure. In a LIFO data structure, the last element added to the structure must be
the first one to be removed.
1
Simple representation of a stack
Queue:
In computer science, a queue is a particular kind of abstract data type or collection in
which the entities in the collection are kept in order and the principal (or only) operations
on the collection are the addition of entities to the rear terminal position, known as
enqueue, and removal of entities from the front terminal position, known as dequeue.
This makes the queue a First-In-First-Out (FIFO) data structure. In a FIFO data structure,
the first element added to the queue will be the first one to be removed.
Representation of a Queue with FIFO (First In First Out) property
List:
In computer science, a list or sequence is an abstract data type that implements an ordered
collection of values, where the same value may occur more than once. An instance of a
list is a computer representation of the mathematical concept of a finite sequence. Each
instance of a value in the list is usually called an item, entry, or element of the list; if the
same value occurs multiple times, each occurrence is considered a distinct item.
2
A singly linked list structure, implementing a list with 3 integer elements.
The name list is also used for several concrete data structures that can be used to
implement abstract lists, especially linked lists.
Tree:
A tree data structure can be defined recursively (locally) as a collection of nodes (starting
at a root node), where each node is a data structure consisting of a value, together with a
list of references to nodes (the "children"), with the constraints that no reference is
duplicated, and none points to the root. A tree can be defined abstractly as a whole
(globally) as an ordered tree, with a value assigned to each node.
A labeled graph
Graph:
A graph data structure consists of a finite (and possibly mutable) set of ordered pairs,
called edges or arcs, of certain entities called nodes or vertices. As in mathematics, an
edge (x,y) is said to point or go from x to y. The nodes may be part of the graph structure,
or may be external entities represented by integer indices or references.
A graph data structure may also associate to each edge some edge value, such as a
symbolic label or a numeric attribute (cost, capacity, length, etc.).
3
A labeled graph of 6 vertices and 7 edges.
Advantages &Disadvantages of Data Structure :
Data
Advantages Disadvantages
Structure
Quick insertion, very fast access if index Slow search, slow deletion, fixed
Array
known size.
Ordered Slow insertion and deletion, fixed
Quicker search than unsorted array.
array size.
Stack Provides last-in, first-out access. Slow access to other items.
Queue Provides first-in, first-out access. Slow access to other items.
Linked list Quick insertion, quick deletion. Slow search.
Quick search, insertion, deletion (if tree
Binary tree Deletion algorithm is complex.
remains balanced).
Quick search, insertion, deletion. Tree
Red-black
always balanced. Similar trees good for Complex
tree
disk storage.
Quick search, insertion, deletion. Tree
2-3-4 tree always balanced. Similar tree good for Complex
disk storage.
Slow deletion, access slow if key
Very fast access if key known. Fast
Hash table not known, inefficient memory
insertion.
usage.
Slow access to other items.access
Heap Fast insertion, deletion,
to largest item.
Some algorithms are slow and
Graph Models real-world situations.
complex.
Result :- we have successful study about Data Structure.
4
Experiment No.-02
Aim: Write a C program to implement Stack using Array.
Algorithm
STEP 1:Start
STEP 2:Initialize stack, will=1,i, num
STEP 3:Add element in stack
PUSH(S,TOP,X)
3.a. [Check overflow condition]
If(TOP>=N) then
Write(“Stack is full”)
3.b. [Insert element]
[Increment TOP]
TOP <- TOP+1
S[TOP]<- X
3.c. [Finish the process]
STEP 4: Delete element in stack
POP(S,TOP)
4.a. [Check for underflow condition]
If(TOP <- 0) then
Write(“Stack is empty”)
4.b. [Delete element]
[Decrement TOP]
TOP<- TOP-1
Delete S[TOP+1]
4.c.[Finish the process]
5
STEP 5:Stop
Coding:
#include<stdio.h>
#include<conio.h>
#define size 10
int stack[size],top=0,b;
int res;
void push();
void pop();
void display();
void main()
int c;
clrscr();
printf("\n1.Push\n2.Pop\n3.Display");
do
printf("\n\nEnter your Choice :: ");
scanf("%d",&c);
switch(c)
case 1:
push();
6
break;
case 2:
pop();
break;
case 3:
printf("\n\nContents of stack is \t");
display();
break;
default:
printf("\nInvalid Choice......");
}while(c<4);
getch();
void push()
if(top>=size)
printf("\nStack Overflow");
return;
else
7
printf("\nEnter the number to be pushed into the stack :: ");
scanf("%d",&b);
top++;
stack[top]=b;
printf("\nNumber pushed is %d",stack[top]);
return;
void pop()
if(top==0)
printf("\nStack Underflow");
return;
else
res=stack[top];
top--;
printf("\nDeleted element is %d",res);
return;
void display()
8
{
int i;
if(top==0)
printf("\nStack Underflow");
return;
for(i=top;i>0;i--)
printf("%d , ",stack[i]);
9
Output:
10
Experiment No.-03
Aim: Write a C program to implement Infix to Postfix Conversion.
Algorithm:
STEP 1: Start
STEP 2: Initialize the stack.
STEP 3: While (INSTR!= NULL)
STEP 4: CH= get the character from INSTR.
STEP 5: If( CH= = operand) then
append CH int POSTSTR
else if(CH = = ‘(‘) then
11
push CH into stack
else if(CH = =’)’) then
pop the data from the stack and append the data into POSTSTR until we get
‘(‘ from the stack
else
while(precedence (TOP) >= precedence (CH))
pop the data from stack and append the data into POSTSTR.
[End of while structure]
[End of if structure]
STEP 6: Push CH into the stack.
STEP 7: [End of second while structure]
STEP 8: pop all the data from stack and append data into POSTSTR.
STEP 9: Stop
Coding:
#include<stdio.h>
#include<conio.h>
int stack[20],top=0;
char inf[40],post[40];
void push(int);
void postfix();
char pop();
void main(void)
12
clrscr();
printf("\t\t\t****INFIX TO POSTFIX****\n\n");
printf("Enter the infix expression :: ");
scanf("%s",inf);
postfix();
getch();
void postfix()
int i,j=0;
for(i=0;inf[i]!=NULL;i++)
switch(inf[i])
case '+':
while(stack[top]>=1)
post[j++]=pop();
push(1);
break;
case '-':
while(stack[top]>=1)
post[j++]=pop();
push(2);
break;
13
case '*':
while(stack[top]>=3)
post[j++]=pop();
push(3);
break;
case '/':
while(stack[top]>=3)
post[j++]=pop();
push(4);
break;
case '^':
while(stack[top]>=4)
post[j++]=pop();
push(5);
break;
case '(':
push(0);
break;
case ')':
while(stack[top]!=0)
post[j++]=pop();
top--;
break;
default:
14
post[j++]=inf[i];
while(top>0)
post[j++]=pop();
printf("\nPostfix Expression is :: %s",post);
void push(int ele)
top++;
stack[top]=ele;
char pop()
char e;
e=stack[top];
top--;
switch(e)
case 1:
e='+';
break;
case 2:
e='-';
15
break;
case 3:
e='*';
break;
case 4:
e='/';
break;
case 5:
e='^';
break;
return(e);
Output:
16
Manual Calculation
SE EXPRESSION STACK RESULT FIELD
( (
A A
+ +,( A
17
B +,( AB
) ),( AB+
/ / AB+
( (,/
C (,/ AB+C
- -,(,/ AB+C
D -,(,/ AB+CD
+ +,(,/ AB+CD-
E +,(,/ AB+CD-E
) ),+,(,/ AB+CD-E+
+ +,/ AB+CD-E+/
F + AB+CD-E/F
- - AB+CD-E/F+
G - AB+CD-E/F+G
AB+CD-E/F+G-
Experiment No.-04
Aim: Write a C program To Implement Queue Using Array.
Algorithm
STEP 1: Start
STEP 2: [Include all header files]
18
STEP 3: [Declare the variables]
STEP 4: [If n->1 call the function Enqueue( )]
STEP 5: [If n->2 call the function Dequeue( )]
STEP 6: [If n->3 call the function Peep( )]
STEP 7: [If n->4 call the function Size( )]
STEP 8: [If n->5 call the function View( )]
STEP 9: [else Exit( )]
STEP 10: Stop
Coding:
#include<stdio.h>
#include<conio.h>
#define size 15
int queue[size],front=0,rear=0,b;
int res;
void enqueue();
void dequeue();
void display();
void main()
{
int c;
clrscr();
printf("\n1.Insertion\t2.Deletion\t3.Display");
do
{
printf("\nEnter your Choice :: ");
scanf("%d",&c);
switch(c)
{
case 1:
enqueue();
break;
case 2:
19
dequeue();
break;
case 3:
printf("\nContents of queue is \t");
display();
break;
default:
printf("\nInvalid Choice......");
}
}while(c<4);
getch();
}
void enqueue()
{
if(rear>=size)
{
printf("\nOverflow");
return;
}
else
{
printf("\nEnter the number to be entered :: ");
scanf("%d",&b);
rear++;
queue[rear]=b;
printf("\nNumber pushed is %d",queue[rear]);
if(front==0)
front=1;
return;
}
}
void dequeue()
{
if(front==0)
{
printf("\nUnderflow");
return;
}
else
{
res=queue[front];
if(front==rear)
20
{
front=0;
rear=0;
}
else
front++;
}
printf("\nDeleted element is %d",res);
return;
}
void display()
{
int i;
if(front==0)
{
printf("\nUnderflow");
return;
}
for(i=front;i<=rear;i++)
printf("%d , ",queue[i]);
}
Output:
21
22
Experiment No.-05
Aim: Write a C program to implement and Creation of Binary search tree.
Algorithm
1. [Include all the necessary header files.]
2. [Declare the structure with all necessary variables.]
3. Read x;
4. Call INORDER().
5. Call PREORDER().
6. Call POSTORDER().
7. Call display().
8.
Algorithm For INSERT(P,X)
1. If (pNULL)
Create P
P<-datax.
P->lchild PrchildNULL
Else
2.1 while(TEMP!=NULL)
2.2 Temp2Temp1
2.3 If(temp1datax)
2.4 Else Temp1Temp1rchild
2.5 [End of while structure]
2.6 If(temp2datax)
2.7 Temp 2Temp2lchild
2.8 Temp 2datax
2.9 Temp2dataslchildtemp2rchild Null
2.10 Else
2.11 Temp 2Temp2Temp2rchildnull
2.12 Temp2datax
2.13 Temp 2lchildTemp 2rchildnull
23
2.14 [Return P]
Algorithm For INORDER(p)
1.If(p!=Null)
2. CALL INORDER (pxdhild)
3. WRITE(Ddata)
4.CALL INORDER (prchild)
5. [End the function]
Algorithm for PREORDER
1. If (pl=NULL)
2. WRITE (PData)
3. CALL PREORDER (PlCHILD)
4. CALL PREORDER (P Rchild)
5. [END OF FUNTION]
Algorithm for POSTORDER
1. If (P!=NULL)
2. Call POSTORDER (Plchild)
3. Call POSTORDER (Prchild)
4. Write (Pdata)
5. [End of function]
Algorithm for COUNT
If (P==NULL)
1. Return 0
2. Else
3. [Return (1+count(Plchild)+call count(Prchild)) ]
4. Algorithm for postorder
Algorithm for DISPLAY
If (T!=NULL)
1. X(lm+rm)/2
2. Call goto xy (x,4*y)
3. Write (t--.data)
4. Call display (tlchild, lm,x, l+1)
24
5. Call display (trchild, x, rm,l+1)
6. [END THE FUNCTION}
Algorithm for SEARCH
1. while(temp!=NULL)
2. If (tempdatat)
[Return temp]
3.If (Tempdata>x)
Temptemplchild
4. ELSE
Temptemprchild
5. [RETURN NULL]
Coding:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define NULL 0
struct treenode
{ int element;
struct treenode *left;
struct treenode *right;
};
typedef struct treenode *position,*searchtree;
25
searchtree insert(int x,searchtree t)
if(t==NULL)
{
t=(struct treenode*)malloc(sizeof(struct treenode));
if(t==NULL)
exit(0);
else
{
t->element=x;
t->left=t->right=NULL;
}
}
else
if(x<t->element)
t->left=insert(x,t->left);
else
if(x>t->element)
t->right=insert(x,t->right);
return t;
}
position findmin(searchtree t)
{
if(t==NULL)
return NULL;
else
if(t->left==NULL)
return t;
else
return findmin(t->left);
}
position findmax(searchtree t)
{
if(t==NULL)
return NULL;
else
if(t->right==NULL)
return t;
else
return findmax(t->right);
26
}
searchtree rem(int x,searchtree t)
{
position temp;
if(t==NULL)
printf("\nElement not found");
else
if(x<t->element)
t->left=rem(x,t->left);
else
if(x>t->element)
t->right=rem(x,t->right);
else
if(t->left&&t->right)
{
temp=findmin(t->right);
t->element=temp->element;
t->right=rem(t->element,t->right);
}
else
{
temp=t;
if(t->left==NULL)
t=t->right;
else
if(t->right==NULL)
t=t->left;
free(temp);
}
return t;
}
void intrav(searchtree head)
{
if(head==NULL)
return;
if(head->left!=NULL)
intrav(head->left);
printf("%d\t",head->element);
if(head->right!=NULL)
intrav(head->right);
27
}
void main()
{
int n,i,dat,ch;
searchtree t=NULL;
position node;
clrscr();
printf("Enter no of elements:\n");
scanf("%d",&n);
printf("Enter the elements:\n");
for(i=1;i<=n;i++)
{
scanf("%d",&dat);
t=insert(dat,t);
}
intrav(t);
do
{
printf("\n\n");
printf("\n ****MENU****\n");
printf("\nEnter 1 -> Insert a node\n");
printf("\n 2 -> Delete a node\n");
printf("\n 3 -> Find Minimum\n");
printf("\n 4 -> Find Maximum\n");
printf("\n 5 -> Display(Inorder Traversal\n");
printf("\n 6 -> Exit\n");
printf("\nEnter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:printf("\nEnter the element to be inserted:");
scanf("%d",&dat);
t=insert(dat,t);
break;
case 2:printf("\n Enter the node to be deleted:");
scanf("%d",&dat);
t=rem(dat,t);
break;
case 3:node=findmin(t);
printf("\nThe minimum element is %d",node->element);
break;
case 4:node=findmax(t);
28
printf("\nThe maximum element is %d",node->element);
break;
case 5:intrav(t);
break;
case 6:exit(0);
}
}while(ch!=6);
getch();
}
OUTPUT:
29
30
31
32
Experiment No.-06
Aim: Write a C program for merge sort.
Algorithm:
function merge_sort(list m)
// if list size is 0 (empty) or 1, consider it sorted and return it
// (using less than or equal prevents <span class="IL_AD"
id="IL_AD9">infinite</span> recursion for a zero length m)
if length(m) <= 1
return m
// else list size is > 1, so split the list into two sublists
var list left, right
var <span class="IL_AD" id="IL_AD6">integer</span> middle = length(m) / 2
for each x in m before middle
add x to left
for each x in m after or equal middle
add x <span class="IL_AD" id="IL_AD7">to right</span>
// recursively call merge_sort() to further split each sublist
// until sublist size is 1
left = merge_sort(left)
right = merge_sort(right)
// merge the sublists returned from prior calls to merge_sort()
// and return the resulting merged sublist
return merge(left, right)
Coding:
#include <stdio.h>
#include<conio.h>
void mergesort(int arr[], int l, int h);
void main(void)
{
int array[100],n,i = 0;
clrscr();
33
printf("Enter the number of elements to be sorted: ");
scanf("%d",&n);
printf("\nEnter the elements to be sorted: \n");
for(i = 0 ; i < n ; i++ )
{
printf("\tArray[%d] = ",i);
scanf("%d",&array[i]);
}
printf("\nBefore Mergesort:"); //Array Before Mergesort
for(i = 0; i < n; i++)
{
printf("%4d", array[i]);
}
printf("\n");
mergesort(array, 0, n - 1);
printf("\nAfter Mergesort:"); //Array After Mergesort
for(i = 0; i < n; i++)
{
printf("%4d", array[i]);
}
printf("\n");
getch();
}
void mergesort(int arr[], int l, int h)
{
int i = 0;
int length = h - l + 1;
int pivot = 0;
int merge1 = 0;
int merge2 = 0;
int temp[100];
34
if(l == h)
return;
pivot = (l + h) / 2;
mergesort(arr, l, pivot);
mergesort(arr, pivot + 1, h);
for(i = 0; i < length; i++)
{
temp[i] = arr[l + i];
}
merge1 = 0;
merge2 = pivot - l + 1;
for(i = 0; i < length; i++)
{
if(merge2 <= h - l)
{
if(merge1 <= pivot - l)
{
if(temp[merge1] > temp[merge2])
{
arr[i + l] = temp[merge2++];
}
else
{
arr[i + l] = temp[merge1++];
}
}
else
{
arr[i + l] = temp[merge2++];
}
35
}
else
{
arr[i + l] = temp[merge1++];
}
}
}
36
Output:
37
Experiment No.-07
Aim: Write a C program for Bubble sort.
Algorithm:
Step 1: Repeat Steps 2 and 3 for i=1 to 10
Step 2: Set j=1
Step 3: Repeat while j<=n
(A) if a[i] < a[j]
Then interchange a[i] and a[j]
[End of if]
(B) Set j = j+1
[End of Inner Loop]
[End of Step 1 Outer Loop]
Step 4: Exit
38
Coding:
#include<stdio.h>
#include<conio.h>
void main()
{
int i,n,temp,j,arr[25];
clrscr();
printf("Enter the number of elements in the Array: ");
scanf("%d",&n);
printf("\nEnter the elements:\n\n");
for(i=0 ; i<n ; i++)
{
printf(" Array[%d] = ",i);
scanf("%d",&arr[i]);
}
for(i=0 ; i<n ; i++)
{
for(j=0 ; j<n-i-1 ; j++)
{
if(arr[j]>arr[j+1]) //Swapping Condition is Checked
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
printf("\nThe Sorted Array is:\n\n");
for(i=0 ; i<n ; i++)
{
printf(" %4d",arr[i]);
}
getch();
}
39
Output:
40
Experiment No.-08
Aim: Write a C program for Quick sort.
Algorithm:
function quicksort('array')
if length('array') ≤ 1
return 'array' // an array of zero or one elements is already sorted
select and remove a pivot value 'pivot' from 'array'
create empty lists 'less' and 'greater'
for each 'x' in 'array'
if 'x' ≤ 'pivot' then append 'x' to 'less'
else append 'x' to 'greater'
return concatenate(quicksort('less'), 'pivot', quicksort('greater'))
// two recursive calls
Coding:
#include<stdio.h>
#include<conio.h>
void quick_sort(int arr[20],int,int);
void main()
41
{
int arr[20],n,i;
clrscr();
printf("Enter the number of elements in the Array: ");
scanf("%d",&n);
printf("\nEnter %d elements:\n\n",n);
for(i=0 ; i<n ; i++)
{
printf(" Array[%d] = ",i);
scanf("%d",&arr[i]);
}
quick_sort(arr,0,n-1);
printf("\nThe Sorted Array is:\n\n");
for(i=0 ; i<n ; i++)
{
printf(" %4d",arr[i]);
}
getch();
}
void quick_sort(int arr[20],int low,int high)
{
int pivot,j,temp,i;
if(low<high)
{
pivot = low;
i = low;
j = high;
while(i<j)
{
while((arr[i]<=arr[pivot])&&(i<high))
{
i++;
42
}
while(arr[j]>arr[pivot])
{
j--;
}
if(i<j)
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
temp=arr[pivot];
arr[pivot]=arr[j];
arr[j]=temp;
quick_sort(arr,low,j-1);
quick_sort(arr,j+1,high);
}
}
43
Output:
44
Experiment No.-09
Aim: - Study about graph in detail.
Introduction: -A graph is a mathematical structure consisting of a set of vertices (also
called nodes) and a set of edges . An edge is a pair of
vertices . The two vertices are called the edge endpoints. Graphs
are ubiquitous in computer science. They are used to model real-world systems such as
the Internet (each node represents a router and each edge represents a connection between
routers); airline connections (each node is an airport and each edge is a flight); or a city
road network (each node represents an intersection and each edge represents a block).
The wireframe drawings in computer graphics are another example of graphs.
A graph may be either undirected or directed. Intuitively, an undirected edge models a
"two-way" or "duplex" connection between its endpoints, while a directed edge is a one-
way connection, and is typically drawn as an arrow. A directed edge is often called an
arc. Mathematically, an undirected edge is an unordered pair of vertices, and an arc is an
ordered pair. For example, a road network might be modeled as a directed graph, with
one-way streets indicated by an arrow between endpoints in the appropriate direction, and
two-way streets shown by a pair of parallel directed edges going both directions between
the endpoints. You might ask, why not use a single undirected edge for a two-way street.
There's no theoretical problem with this, but from a practical programming standpoint,
it's generally simpler and less error-prone to stick with all directed or all undirected
edges.
45
An undirected graph can have at most edges (one for each unordered pair),
while a directed graph can have at most edges (one per ordered pair). A graph is called
sparse if it has many fewer than this many edges (typically edges), and dense if it
has closer to edges. A multigraph can have more than one edge between the same
two vertices. For example, if one were modeling airline flights, there might be multiple
flights between two cities, occurring at different times of the day.
A path in a graph is a sequence of vertices such that there exists an
edge or arc between consecutive vertices. The path is called a cycle if . An
undirected acyclic graph is equivalent to an undirected tree. A directed acyclic graph is
called a DAG. It is not necessarily a tree.
Nodes and edges often have associated information, such as labels or weights. For
example, in a graph of airline flights, a node might be labeled with the name of the
corresponding airport, and an edge might have a weight equal to the flight time. The
popular game "Six Degrees of Kevin Bacon" can be modeled by a labeled undirected
graph. Each actor becomes a node, labeled by the actor's name. Nodes are connected by
an edge when the two actors appeared together in some movie. We can label this edge by
the name of the movie. Deciding if an actor is separated from Kevin Bacon by six or
fewer steps is equivalent to finding a path of length at most six in the graph between
Bacon's vertex and the other actors vertex.
Directed Graphs
A directed graph.
The number of edges with one endpoint on a given vertex is called that vertex's degree.
In a directed graph, the number of edges that point to a given vertex is called its in-
degree, and the number that point from it is called its out-degree. Often, we may want to
46
be able to distinguish between different nodes and edges. We can associate labels with
either. We call such a graph labeled.
Undirected Graphs
An undirected graph.
In a directed graph, the edges point from one vertex to another, while in an undirected
graph, they merely connect two vertice
Weighted Graphs
We may also want to associate some cost or weight to the traversal of an edge. When we
add this information, the graph is called weighted. An example of a weighted graph
would be the distance between the capitals of a set of countries.
Directed and undirected graphs may both be weighted. The operations on a weighted
graph are the same with addition of a weight parameter during edge creation:
Graph Representations
Adjacency Matrix Representation
An adjacency matrix is one of the two common ways to represent a graph. The
adjacency matrix shows which nodes are adjacent to one another. Two nodes are
adjacent if there is an edge connecting them. In the case of a directed graph, if node is
adjacent to node , there is an edge from to . In other words, if is adjacent to , you
can get from to by traversing one edge. For a given graph with nodes, the adjacency
matrix will have dimensions of . For an unweighted graph, the adjacency matrix
will be populated with boolean values.
47
For any given node , you can determine its adjacent nodes by looking at row
of the adjacency matrix. A value of true at indicates that there is an edge from node
to node , and false indicating no edge. In an undirected graph, the values of and
will be equal. In a weighted graph, the boolean values will be replaced by the
weight of the edge connecting the two nodes, with a special value that indicates the
absence of an edge.The memory use of an adjacency matrix is .
Adjacency List Representation
The adjacency list is another common representation of a graph. There are many ways to
implement this adjacency representation. One way is to have the graph maintain a list of
lists, in which the first list is a list of indices corresponding to each node in the graph.
Each of these refer to another list that stores a the index of each adjacent node to this one.
It might also be useful to associate the weight of each link with the adjacent node in this
list.
Example: An undirected graph contains four nodes 1, 2, 3 and 4. 1 is linked to 2 and 3. 2
is linked to 3. 3 is linked to 4.
1 - [2, 3]
2 - [1, 3]
3 - [1, 2, 4]
4 - [3]
It might be useful to store the list of all the nodes in the graph in a hash table. The keys
then would correspond to the indices of each node and the value would be a reference to
the list of adjacent node indices.
Another implementation might require that each node keep a list of its adjacent nodes.
Conclusion: - We have successfully study about graph.
48
49