0% found this document useful (0 votes)
313 views

Ds Lab Manual - 2018

The document describes a C program that implements a list data structure using arrays. It defines functions for common list operations like insertion, deletion, searching, and printing. The main function allows the user to choose an operation to perform on the list and test the functions, like inserting multiple elements at the end of the list and then printing the list.

Uploaded by

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

Ds Lab Manual - 2018

The document describes a C program that implements a list data structure using arrays. It defines functions for common list operations like insertion, deletion, searching, and printing. The main function allows the user to choose an operation to perform on the list and test the functions, like inserting multiple elements at the end of the list and then printing the list.

Uploaded by

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

EX.

NO:1 LIST USING ARRAYS


DATE:
AIM:
To write a C program for the implementation of List ADT using arrays.

ALGORITHM:
Step 1 : Start the program
Step 2 : Declare the required functions to implement the operations of List.
Step 3 : Check whether the List is empty or Full using isEmpty( ) and isFull( )
Step 4 : Insert the elements to the end, Nth position and the beginning of the list by using
insertToEOL( ),insertToNthPos( ) and insertToFOL( ) respectively.
Step 5 : Delete the elements from the end, Nth position and the beginning of the list by using
deleteFromEOL( ), deleteFromNthPos ( ) and deleteFromFOL respectively.
Step 6 : Search the element in the list by using searchInList( )
Step 7 : Print the elements in the list by using printList( )
Step 8: Stop the program

PROGRAM:
#include <stdio.h>
int MAXSIZE=10;
int CURRENTSIZE=0;

int isEmpty()
{
if(CURRENTSIZE==0)
{
return 1;
}
else return 0;

int isFull()
{
if(CURRENTSIZE==MAXSIZE)
{
return 1;
}
else return 0;
}

void insertToEOL(int *Listptr)


{
if(isFull())
{
printf("List is Full Can’t Insert\n");
}
else
{
int element;
printf("Enter the Element to Insert\n");
scanf("%d",&element);
int index=CURRENTSIZE;
Listptr[index]=element;
CURRENTSIZE=CURRENTSIZE+1;
}

void deleteFromEOL(int *List)


{
if(isEmpty())
{
printf("List is Empty. We cant Delete\n");
}
else
{
int element;
int index=CURRENTSIZE-1;
element=List[index];
printf("Element %d deleted from position %d\n",element,index+1);
CURRENTSIZE=CURRENTSIZE-1;
}

}
void insertToFOL(int *List)
{

if(isFull())
{
printf("List is Full... cant insert\n");
}
else
{
int index=0,element;
printf("Enter the element to insert\n");
scanf("%d",&element);

for(index=CURRENTSIZE;index>0;index--)
{
List[index]=List[index-1];
}
List[0]=element;
CURRENTSIZE=CURRENTSIZE+1;
}
}

void deleteFromFOL(int *List)


{
if(isEmpty())
{
printf("List is Empty... cant delete\n"); }
else//else
{
int index=0,element;
element=List[0];
for(index=0;index<CURRENTSIZE;index++)
{
List[index]=List[index+1];
}
CURRENTSIZE=CURRENTSIZE-1;
printf("Element %d from Position 1\n",element);
}}
void insertToNthPos(int *List)
{
if(isFull())
{
printf("List is Full... Cant insert\n");
}
else
{
int i,index=0,element,pos;
printf("Available Position in LIst\n");
if(isEmpty())
{
printf("List is Empty... only Available Position is 1\n");
printf("Enter the Element to insert\n");
scanf("%d",&element);
List[0]=element;
CURRENTSIZE=CURRENTSIZE+1;
}
else
{
do
{
printf("Enter the Position(within %d from 1) in which you want to insert
Element\n",CURRENTSIZE);
scanf("%d",&pos);

}while(pos>CURRENTSIZE || pos<0);

printf("Enter the Element to insert\n");


scanf("%d",&element);//Get the element
for(index=CURRENTSIZE;index>pos-1;index--)
{
List[index]=List[index-1]; }
List[pos-1]=element;
CURRENTSIZE=CURRENTSIZE+1;
}
}

}
void deleteFromNthPos(int *List)
{
int element,pos,index;
if(isEmpty())
{
printf("List is Empty... cant delete\n");
}
else
{
do
{
printf("Enter the Position(within %d from 1) from which you want to Delete
Element\n",CURRENTSIZE);
scanf("%d",&pos);
}while(pos>CURRENTSIZE || pos<0);
element=List[pos-1];
if(pos==CURRENTSIZE)
{
CURRENTSIZE=CURRENTSIZE-1;
}
else {
for(index=pos-1;index<CURRENTSIZE;index++)
{
List[index]=List[index+1];
}
CURRENTSIZE=CURRENTSIZE-1; }
printf("Element %d deleted from position %d\n",element,pos);
}
printf("deleteFromNthPos\n");
}

void searchInList(int *List)


{
int element,index,i,found=0;
if(isEmpty()) {
printf("List is empty\n");
}
else {
printf("Enter the Element to search\n");
scanf("%d",&element);
for(i=0;i<CURRENTSIZE;i++)
{
if(List[i]==element)
{
found=1;
break;
}
}
if(found)
printf("Element %d available in Position %d\n",element,i+1);
else
printf("Element %d not available in List\n",element); }
}

void printList(int List[])


{
int i=0;
if(isEmpty())
{
printf("List is Empty\n");
}
else
{
printf("***Position--->Value***\n");
for(i=0;i<CURRENTSIZE;i++)
{
printf(" %d--------->%d\n",i+1,List[i]);
}
}
printf("***List Current Status***\n");
printf("MAXSIZE =%d\n",MAXSIZE);
printf("CURRENTSIZE=%d\n",CURRENTSIZE);
}

int main()
{
int List[MAXSIZE];//List array
int iChoice=0,r=0;
do
{
printf("--------------Array Implementation Of List-----------\n");
printf("\t\t1. is Empty\n\t\t2. is Full\n\t\t3. Insert Element to End of LIST\n\t\t4. Delete
Element from End of LIST\n\t\t5. Insert Element to Front of LIST\n\t\t6. Delete Element
from Front of LIST\n\t\t7. Insert Element to Nth Position of LIST\n\t\t8. Delete Element from
Nth Position of LIST\n\t\t9. Search Element in LIST\n\t\t10. print LIST\n\t\t11. Exit\n");
printf("------------------------------------------------------------\n");
printf("Please Enter Ur Choice\n");
scanf("%d",&iChoice);
switch(iChoice)
{
case 1:
r=isEmpty();
//printf("r=%d\n",r);
r==0?printf("List is Not Empty\n"):printf("List is Empty\n");
printf("------------------------------------------------------------\n");
break;
case 2:
r=isFull();
r==0?printf("List is Not Full\n"):printf("List is Full\n");
printf("------------------------------------------------------------\n");
break;
case 3:
insertToEOL(List);
printf("------------------------------------------------------------\n");
break;
case 4:
deleteFromEOL(List);
printf("------------------------------------------------------------\n");
break;
case 5:
insertToFOL(List);
printf("------------------------------------------------------------\n");
break;
case 6:
deleteFromFOL(List);
printf("------------------------------------------------------------\n");
break;
case 7:
insertToNthPos(List);
printf("------------------------------------------------------------\n");
break;
case 8:
deleteFromNthPos(List);
printf("------------------------------------------------------------\n");
break;
case 9:
searchInList(List);
printf("------------------------------------------------------------\n");
break;
case 10:
printList(List);
printf("------------------------------------------------------------\n");
break;
case 11:
break;

default:
printf("=============================================================
==\n");
printf("\t\tHi !You have not entered the right choice\n");

printf("=============================================================
==\n");
}
}while(iChoice!=11);
system("PAUSE");
}

OUTPUT:
--------------Array Implementation Of List-----------
1. is Empty
2. is Full
3. Insert Element to End of LIST
4. Delete Element from End of LIST
5. Insert Element to Front of LIST
6. Delete Element from Front of LIST
7. Insert Element to Nth Position of LIST
8. Delete Element from Nth Position of LIST
9. Search Element in LIST
10. print LIST
11. Exit
------------------------------------------------------------
Please Enter Ur Choice
3
Enter the Element to Insert
33
------------------------------------------------------------
--------------Array Implementation Of List-----------
1. is Empty
2. is Full
3. Insert Element to End of LIST
4. Delete Element from End of LIST
5. Insert Element to Front of LIST
6. Delete Element from Front of LIST
7. Insert Element to Nth Position of LIST
8. Delete Element from Nth Position of LIST
9. Search Element in LIST
10. print LIST
11. Exit
------------------------------------------------------------
Please Enter Ur Choice
3
Enter the Element to Insert
45
------------------------------------------------------------
--------------Array Implementation Of List-----------
1. is Empty
2. is Full
3. Insert Element to End of LIST
4. Delete Element from End of LIST
5. Insert Element to Front of LIST
6. Delete Element from Front of LIST
7. Insert Element to Nth Position of LIST
8. Delete Element from Nth Position of LIST
9. Search Element in LIST
10. print LIST
11. Exit
------------------------------------------------------------
Please Enter Ur Choice
3
Enter the Element to Insert
28
------------------------------------------------------------
--------------Array Implementation Of List-----------
1. is Empty
2. is Full
3. Insert Element to End of LIST
4. Delete Element from End of LIST
5. Insert Element to Front of LIST
6. Delete Element from Front of LIST
7. Insert Element to Nth Position of LIST
8. Delete Element from Nth Position of LIST
9. Search Element in LIST
10. print LIST
11. Exit
------------------------------------------------------------
Please Enter Ur Choice
10
***Position--->Value***
1--------->33
2--------->45
3--------->28
***List Current Status***
MAXSIZE =10
CURRENTSIZE=3
------------------------------------------------------------
--------------Array Implementation Of List-----------
1. is Empty
2. is Full
3. Insert Element to End of LIST
4. Delete Element from End of LIST
5. Insert Element to Front of LIST
6. Delete Element from Front of LIST
7. Insert Element to Nth Position of LIST
8. Delete Element from Nth Position of LIST
9. Search Element in LIST
10. print LIST
11. Exit
------------------------------------------------------------
Please Enter Ur Choice
9
Enter the Element to search
45
Element 45 available in Position 2
------------------------------------------------------------
--------------Array Implementation Of List-----------
1. is Empty
2. is Full
3. Insert Element to End of LIST
4. Delete Element from End of LIST
5. Insert Element to Front of LIST
6. Delete Element from Front of LIST
7. Insert Element to Nth Position of LIST
8. Delete Element from Nth Position of LIST
9. Search Element in LIST
10. print LIST
11. Exit
------------------------------------------------------------
Please Enter Ur Choice
5
Enter the element to insert
37
------------------------------------------------------------
--------------Array Implementation Of List-----------
1. is Empty
2. is Full
3. Insert Element to End of LIST
4. Delete Element from End of LIST
5. Insert Element to Front of LIST
6. Delete Element from Front of LIST
7. Insert Element to Nth Position of LIST
8. Delete Element from Nth Position of LIST
9. Search Element in LIST
10. print LIST
11. Exit
------------------------------------------------------------
Please Enter Ur Choice
10
***Position--->Value***
1--------->37
2--------->33
3--------->45
4--------->28
***List Current Status***
MAXSIZE =10
CURRENTSIZE=4
------------------------------------------------------------
--------------Array Implementation Of List-----------
1. is Empty
2. is Full
3. Insert Element to End of LIST
4. Delete Element from End of LIST
5. Insert Element to Front of LIST
6. Delete Element from Front of LIST
7. Insert Element to Nth Position of LIST
8. Delete Element from Nth Position of LIST
9. Search Element in LIST
10. print LIST
6
Element 37 from Position 1
------------------------------------------------------------
--------------Array Implementation Of List-----------
1. is Empty
2. is Full
3. Insert Element to End of LIST
4. Delete Element from End of LIST
5. Insert Element to Front of LIST
6. Delete Element from Front of LIST
7. Insert Element to Nth Position of LIST
8. Delete Element from Nth Position of LIST
9. Search Element in LIST
10. print LIST
11. Exit
------------------------------------------------------------
Please Enter Ur Choice
10
***Position--->Value***
1--------->33
2--------->45
3--------->28
***List Current Status***
MAXSIZE =10
CURRENTSIZE=3
------------------------------------------------------------
--------------Array Implementation Of List-----------
1. is Empty
2. is Full
3. Insert Element to End of LIST
4. Delete Element from End of LIST
5. Insert Element to Front of LIST
6. Delete Element from Front of LIST
7. Insert Element to Nth Position of LIST
8. Delete Element from Nth Position of LIST
9. Search Element in LIST
10. print LIST
11. Exit
------------------------------------------------------------
Please Enter Ur Choice 11

RESULT:
Thus a C program for List ADT using arrays was implemented and executed
successfully.
EX. NO:2 LIST USING SINGLY LINKED LIST
DATE:
AIM:
To write a C program for the implementation of List ADT using Singly Linked List.

ALGORITHM:
Step 1 : Start the program
Step 2 : Declare the required structures and functions to implement the operations of Linked
List.
Step 3 : Insert the element in the list at a particular position using Insert( ).
Step 4 : Delete the elements from the list using Delete( )
Step 5 : Find the previous element in the list by using FindPrevious( )
Step 6 : Merge two lists using Merge( )
Step 7 : Print the elements in the list by using Display( )
Step 8: Stop the program

PROGRAM:
#include<stdio.h>
#include<stdlib.h>
struct Node;
typedef struct Node * PtrToNode;
typedef PtrToNode List;
typedef PtrToNode Position;

struct Node
{
int e;
Position next;
};

void Insert(int x, List l, Position p)


{
Position TmpCell;
TmpCell = (struct Node*) malloc(sizeof(struct Node));
if(TmpCell == NULL)
printf("Memory out of space\n");
else
{
TmpCell  e = x;
TmpCell  next = p  next;
p  next = TmpCell;
}
}
int isLast(Position p)
{
return (p  next == NULL);
}
Position FindPrevious(int x, List l)
{
Position p = l;
while(p  next != NULL && p  next  e != x)
p = p  next;
return p;
}

void Delete(int x, List l)


{
Position p, TmpCell;
p = FindPrevious(x, l);

if(!isLast(p))
{
TmpCell = p  next;
p  next = TmpCell  next;
free(TmpCell);
}
else
printf("Element does not exist!!!\n");
}

void Display(List l)
{
printf("The list element are :: ");
Position p = l  next;
while(p != NULL)
{
printf("%d  ", p  e);
p = p  next;
}
}

void Merge(List l, List l1)


{
int i, n, x, j;
Position p;
printf("Enter the number of elements to be merged :: ");
scanf("%d",&n);

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


{
p = l1;
scanf("%d", &x);
for(j = 1; j < i; j++)
p = p  next;
Insert(x, l1, p);
}
printf("The new List :: ");
Display(l1);
printf("The merged List ::");
p = l;
while(p  next != NULL)
{
p = p  next;
}
p  next = l1  next;
Display(l);
}

int main()
{
int x, pos, ch, i;
List l, l1;
l = (struct Node *) malloc(sizeof(struct Node));
l  next = NULL;
List p = l;
printf("LINKED LIST IMPLEMENTATION OF LIST ADT\n\n");
do
{
printf("\n\n1. INSERT\t 2. DELETE\t 3. MERGE\t 4. PRINT\t 5. QUIT\n\nEnter the
choice :: ");
scanf("%d", &ch);
switch(ch)
{
case 1:
p = l;
printf("Enter the element to be inserted :: ");
scanf("%d",&x);
printf("Enter the position of the element :: ");
scanf("%d",&pos);

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


{
p = p  next;
}
Insert(x,l,p);
break;

case 2:
p = l;
printf("Enter the element to be deleted :: ");
scanf("%d",&x);
Delete(x,p);
break;
case 3:
l1 = (struct Node *) malloc(sizeof(struct Node));
l1  next = NULL;
Merge(l, l1);
break;

case 4:
Display(l);
break;
}
}
while(ch<5);
return 0;
}
OUTPUT:
LINKED LIST IMPLEMENTATION OF LIST ADT

1. INSERT 2. DELETE 3. MERGE 4. PRINT 5. QUIT

Enter the choice :: 1


Enter the element to be inserted :: 10
Enter the position of the element :: 1

1. INSERT 2. DELETE 3. MERGE 4. PRINT 5. QUIT

Enter the choice :: 1


Enter the element to be inserted :: 20
Enter the position of the element :: 2

1. INSERT 2. DELETE 3. MERGE 4. PRINT 5. QUIT

Enter the choice :: 1


Enter the element to be inserted :: 30
Enter the position of the element :: 3

1. INSERT 2. DELETE 3. MERGE 4. PRINT 5. QUIT

Enter the choice :: 4


The list element are :: 10 -> 20 -> 30 ->

1. INSERT 2. DELETE 3. MERGE 4. PRINT 5. QUIT

Enter the choice :: 5

RESULT:
Thus the C program for List ADT using Singly Linked List was implemented and
executed successfully.
EX. NO:3 STACK USING ARRAYS
DATE:
AIM:
To write a C program for the implementation of Stack using arrays.

ALGORITHM:
Step 1 : Start the program
Step 2 : Declare the required functions to implement the operations of Stack.
Step 3 : Check whether the stack is full. If not full, push (insert) the element onto the stack using
push( ) by incrementing the top pointer by 1.
Step 4 : Check whether the stack is empty. If not empty, pop (delete) the element from the stack
using pop( ) by decrementing the top pointer by 1.
Step 5 : Display the contents of the stack using display( )
Step 6 : Stop the program

PROGRAM:
#include<stdio.h>

int stack[100],choice,n,top,x,i;
void push(void);
void pop(void);
void display(void);
int main()
{
//clrscr();
top=-1;
printf("\n Enter the size of STACK[MAX=100]:");
scanf("%d",&n);
printf("\n\t STACK OPERATIONS USING ARRAY");
printf("\n\t--------------------------------");
printf("\n\t 1.PUSH\n\t 2.POP\n\t 3.DISPLAY\n\t 4.EXIT");
do
{
printf("\n Enter the Choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
push();
break;
}
case 2:
{
pop();
break;
}
case 3:
{
display();
break;
}
case 4:
{
printf("\n\t EXIT POINT ");
break;
}
default:
{
printf ("\n\t Please Enter a Valid Choice(1/2/3/4)");
}

}
}
while(choice!=4);
return 0;
}
void push()
{
if(top>=n-1)
{
printf("\n\tStack is over flow");

}
else
{
printf(" Enter a value to be pushed:");
scanf("%d",&x);
top++;
stack[top]=x;
}
}
void pop()
{
if(top<=-1)
{
printf("\n\t Stack is under flow");
}
else
{
printf("\n\t The popped elements is %d",stack[top]);
top--;
}
}
void display()
{
if(top>=0)
{
printf("\n The elements in STACK \n");
for(i=top; i>=0; i--)
printf("\n%d",stack[i]);
printf("\n Press Next Choice");
}
else
{
printf("\n The STACK is empty");
}

OUTPUT:
Enter the size of STACK[MAX=100]:10

STACK OPERATIONS USING ARRAY


--------------------------------
1.PUSH
2.POP
3.DISPLAY
4.EXIT
Enter the Choice:1
Enter a value to be pushed:12

Enter the Choice:1


Enter a value to be pushed:24

Enter the Choice:1


Enter a value to be pushed:98

Enter the Choice:3

The elements in STACK


98
24
12
Press Next Choice
Enter the Choice:2

The popped elements is 98


Enter the Choice:3

The elements in STACK


24
12
Press Next Choice
Enter the Choice:4

RESULT:
Thus a C program for Stack using arrays was implemented and executed successfully.
EX. NO:4 QUEUE USING ARRAYS
DATE:
AIM:
To write a C program for the implementation of Queue using arrays.

ALGORITHM:
Step 1 : Start the program
Step 2 : Declare the required functions to implement the operations of Queue.
Step 3 : Check whether the queue is full. If not full, enqueue (insert) the element into the queue
using enQueue( ) by incrementing the rear pointer by 1.
Step 4 : Check whether the queue is empty. If not empty, dequeue (delete) the element from the
Queue using deQueue( ) by incrementing the front pointer by 1.
Step 5 : Display the contents of the queue using display( )
Step 6 : Stop the program

PROGRAM:
#include<stdio.h>
#include<conio.h>
#define SIZE 10

void enQueue(int);
void deQueue();
void display();

int queue[SIZE], front = -1, rear = -1;

void main()
{
int value, choice;
clrscr();
while(1){
printf("\n\n***** MENU *****\n");
printf("1. Insertion\n2. Deletion\n3. Display\n4. Exit");
printf("\nEnter your choice: ");
scanf("%d",&choice);
switch(choice){
case 1: printf("Enter the value to be insert: ");
scanf("%d",&value);
enQueue(value);
break;
case 2: deQueue();
break;
case 3: display();
break;
case 4: exit(0);
default: printf("\nWrong selection!!! Try again!!!");
} }}
void enQueue(int value){
if(rear == SIZE-1)
printf("\nQueue is Full!!! Insertion is not possible!!!");
else{
if(front == -1)
front = 0;
rear++;
queue[rear] = value;
printf("\nInsertion success!!!");
}
}
void deQueue(){
if(front == rear)
printf("\nQueue is Empty!!! Deletion is not possible!!!");
else{
printf("\nDeleted : %d", queue[front]);
front++;
if(front == rear)
front = rear = -1;
}}
void display(){
if(rear == -1)
printf("\nQueue is Empty!!!");
else{
int i;
printf("\nQueue elements are:\n");
for(i=front; i<=rear; i++)
printf("%d\t",queue[i]); }}

OUTPUT:
***** MENU *****
1. Insertion
2. Deletion
3. Display
4. Exit
Enter your choice: 1
Enter the value to be insert: 22

Insertion success!!!

***** MENU *****


1. Insertion
2. Deletion
3. Display
4. Exit
Enter your choice: 1
Enter the value to be insert: 23

Insertion success!!!

***** MENU *****


1. Insertion
2. Deletion
3. Display
4. Exit
Enter your choice: 1
Enter the value to be insert: 28

Insertion success!!!

***** MENU *****


1. Insertion
2. Deletion
3. Display
4. Exit
Enter your choice: 3

Queue elements are:


22 23 28

***** MENU *****


1. Insertion
2. Deletion
3. Display
4. Exit
Enter your choice: 2

Deleted : 22
***** MENU *****
1. Insertion
2. Deletion
3. Display
4. Exit
Enter your choice: 3

Queue elements are:


23 28

***** MENU *****


1. Insertion
2. Deletion
3. Display
4. Exit
Enter your choice: 4

RESULT:
Thus a C program for Queue using arrays was implemented and executed
successfully.
EX. NO:5 STACK USING LINKED LIST
DATE:
AIM:
To write a C program for the implementation of Stack using Linked list.

ALGORITHM:
Step 1 : Start the program
Step 2 : Declare the required structure and functions to implement the operations of Stack.
Step 3 : Push (insert) the element onto the stack by creating a newnode and insert into the
node using push( ).
Step 4 : Pop (delete) the element from the stack by deleting the node from the linked list
using the pop( )
Step 5 : Display the contents of the stack using display( )
Step 6 : Stop the program

PROGRAM:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

void pop();
void push(int value);
void display();

struct node
{
int data;
struct node *link;
};

struct node *top=NULL,*temp;

void main()
{
int choice,data;

while(1) //infinite loop is used to insert/delete infinite number of elements in stack


{

printf("\n1.Push\n2.Pop\n3.Display\n4.Exit\n");
printf("\nEnter ur choice:");
scanf("%d",&choice);
switch(choice)
{
case 1: //To push a new element into stack

printf("Enter a new element :");


scanf("%d",&data);
push(data);
break;
case 2: // pop the element from stack
pop();
break;

case 3: // Display the stack elements


display();
break;
case 4: // To exit
exit(0);
}

}
getch();
//return 0;
}
void display()
{
temp=top;
if(temp==NULL)
{
printf("\nStack is empty\n");
}
printf("\n The Contents of the Stack are...");
while(temp!=NULL)
{
printf(" %d  ",temp  data);
temp=temp  link;
}

}
void push(int data)
{
temp=(struct node *)malloc(sizeof(struct node)); // creating a space for the new
element.
temp  data=data;
temp  link=top;
top=temp;
display();

void pop()
{
if(top!=NULL)
{
printf("The poped element is %d",top  data);
top=top  link;
}
else
{
printf("\nStack Underflow");
}
display();
}

OUTPUT:
1.Push
2.Pop
3.Display
4.Exit

Enter ur choice:1
Enter a new element :24

1.Push
2.Pop
3.Display
4.Exit
Enter ur choice:1
Enter a new element :28

1.Push
2.Pop
3.Display
4.Exit
Enter ur choice:1
Enter a new element :32

1.Push
2.Pop
3.Display
4.Exit
Enter ur choice:3
The Contents of the Stack are... 32 -> 28 -> 24 ->
1.Push
2.Pop
3.Display
4.Exit

Enter ur choice:2
The poped element is 32
1.Push
2.Pop
3.Display
4.Exit
Enter ur choice:3

The Contents of the Stack are... 28 -> 24 ->


1.Push
2.Pop
3.Display
4.Exit

Enter ur choice:4

RESULT:
Thus a C program for Stack using Linked List was implemented and executed successfully.
EX. NO:6 QUEUE USING LINKED LIST
DATE:
AIM:
To write a C program for the implementation of Queue using Linked list.
ALGORITHM:
Step 1 : Start the program
Step 2 : Declare the required structure and functions to implement the operations of Queue.
Step 3 : Enqueue (insert) the element into the queue by creating a newnode and insert the
element into the node using insert( ).
Step 4 : Dequeue (delete) the element from the queue by deleting the node from the linked list
using the delete( )
Step 5 : Display the contents of the queue using display( )
Step 6 : Stop the program

PROGRAM:
#include<stdio.h>
#include<conio.h>
struct node
{
int info;
struct node *link;
}*front = NULL, *rear = NULL;

void insert();
void delete();
void display();
int item;
void main()
{
int ch;
do
{
printf("\n\n1.\tEnqueue\n2.\tDequeue\n3.\tDisplay\n4.\tExit\n");
printf("\nEnter your choice: ");
scanf("%d", &ch);
switch(ch)
{
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
display();
break;
case 4:
exit(0);
default:
printf("\n\nInvalid choice. Please try again...\n");
}
} while(1);
getch();
}

void insert()
{
printf("\n\nEnter the element to enqueue: ");
scanf("%d", &item);
if(rear == NULL)
{
rear = (struct node *)malloc(sizeof(struct node));
rear  info = item;
rear  link = NULL;
front = rear;
}
else
{
rear  link = (struct node *)malloc(sizeof(struct node));
rear = rear  link;
rear  info = item;
rear  link = NULL;
}}
void delete()
{
struct node *ptr;
if(front == NULL)
printf("\n\nQueue is empty.\n");
else
{
ptr = front;
item = front  info;
front = front  link;
free(ptr);
printf("\n The element that is dequeued(deleted): %d\n", item);
if(front == NULL)
rear = NULL;
}
}

void display()
{
struct node *ptr = front;
if(rear == NULL)
printf("\n\nQueue is empty.\n");
else
{
printf("\n\n");
while(ptr != NULL)
{
printf("%d\t",ptr  info);
ptr = ptr  link;
}
}
}

OUTPUT:
1. Enqueue
2. Dequeue
3. Display
4. Exit

Enter your choice: 1

Enter the element to enqueue: 22


1. Enqueue
2. Dequeue
3. Display
4. Exit

Enter your choice: 1

Enter the element to enqueue: 54


1. Enqueue
2. Dequeue
3. Display
4. Exit
Enter your choice: 1

Enter the element to enqueue: 48

1. Enqueue
2. Dequeue
3. Display
4. Exit

Enter your choice: 3

22 54 48

1. Enqueue
2. Dequeue
3. Display
4. Exit

Enter your choice: 2


The element that is dequeued(deleted): 22

1. Enqueue
2. Dequeue
3. Display
4. Exit

Enter your choice: 3

54 48

1. Enqueue
2. Dequeue
3. Display
4. Exit

Enter your choice: 4

RESULT:
Thus a C program for Queue using Linked List was implemented and executed successfully.
EX. NO: 7(A) POLYNOMIAL ADDITION
DATE:
AIM:
To write a C program to implement Polynomial addition using Linked List.

ALGORITHM:
Step 1 : Start the program
Step 2 : Declare the required structures and functions to implement the operations of Polynomial.
Step 3 : Create the polynomial list using my_create_poly( )
Step 4 : Add the elements of the polynomial expression using my_add_poly( )
Step 5 : Display the result using my_show_poly( )
Step 6 : Stop the program

PROGRAM:
#include<stdio.h>
#include<stdlib.h>

typedef struct link {


int coeff;
int pow;
struct link * next;
} my_poly;

void my_create_poly(my_poly **);


void my_show_poly(my_poly *);
void my_add_poly(my_poly **, my_poly *, my_poly *);

int main(void) {
int ch;
do {
my_poly * poly1, * poly2, * poly3;

printf("\nCreate 1st expression\n");


my_create_poly(&poly1);
printf("\nStored the 1st expression");
my_show_poly(poly1);

printf("\nCreate 2nd expression\n");


my_create_poly(&poly2);
printf("\nStored the 2nd expression");
my_show_poly(poly2);

my_add_poly(&poly3, poly1, poly2);


my_show_poly(poly3);

printf("\nAdd two more expressions? (Y = 1/N = 0): ");


scanf("%d", &ch);
} while (ch);
return 0;
}

void my_create_poly(my_poly ** node) {


int flag; //A flag to control the menu
int coeff, pow;
my_poly * tmp_node; //To hold the temporary last address
tmp_node = (my_poly *) malloc(sizeof(my_poly)); //create the first node
*node = tmp_node; //Store the head address to the reference variable
do {
//Get the user data
printf("\nEnter Coeff:");
scanf("%d", &coeff);
tmp_node  coeff = coeff;
printf("\nEnter Pow:");
scanf("%d", &pow);
tmp_node  pow = pow;
//Done storing user data

//Now increase the Linked on user condition


tmp_node  next = NULL;

//Ask user for continuation


printf("\nContinue adding more terms to the polynomial list?(Y = 1/N = 0): ");
scanf("%d", &flag);
//printf("\nFLAG: %c\n", flag);
//Grow the linked list on condition
if(flag) {
tmp_node  next = (my_poly *) malloc(sizeof(my_poly)); //Grow the list
tmp_node = tmp_node  next;
tmp_node  next = NULL;
}
} while (flag);
}

void my_show_poly(my_poly * node) {


printf("\nThe polynomial expression is:\n");
while(node != NULL) {
printf("%dx^%d", node  coeff, node  pow);
node = node  next;
if(node != NULL)
printf(" + ");
}
}

void my_add_poly(my_poly ** result, my_poly * poly1, my_poly * poly2) {


my_poly * tmp_node; //Temporary storage for the linked list
tmp_node = (my_poly *) malloc(sizeof(my_poly));
tmp_node  next = NULL;
*result = tmp_node; //Copy the head address to the result linked list

printf("\nAddition is completed");
//Loop while both of the linked lists have value
while(poly1 && poly2) {
if (poly1  pow > poly2  pow) {
tmp_node  pow = poly1  pow;
tmp_node  coeff = poly1  coeff;
poly1 = poly1  next;
}
else if (poly1  pow < poly2  pow) {
tmp_node  pow = poly2  pow;
tmp_node  coeff = poly2  coeff;
poly2 = poly2  next;
}
else {
tmp_node  pow = poly1  pow;
tmp_node  coeff = poly1  coeff + poly2  coeff;
poly1 = poly1  next;
poly2 = poly2  next;
}

//Grow the linked list on condition


if(poly1 && poly2) {
tmp_node  next = (my_poly *) malloc(sizeof(my_poly));
tmp_node = tmp_node  next;
tmp_node  next = NULL;
}
}

//Loop while either of the linked lists has value


while(poly1 || poly2) {
//We have to create the list at beginning
//As the last while loop will not create any unnecessary node
tmp_node  next = (my_poly *) malloc(sizeof(my_poly));
tmp_node = tmp_node  next;
tmp_node  next = NULL;

if(poly1) {
tmp_node  pow = poly1  pow;
tmp_node  oeff = poly1  coeff;
poly1 = poly1  next;
}
if(poly2) {
tmp_node  pow = poly2  pow;
tmp_node  coeff = poly2  coeff;
poly2 = poly2  next;
}
}

OUTPUT:
Create 1st expression
Enter Coeff:4
Enter Pow:3

Continue adding more terms to the polynomial list?(Y = 1/N = 0): 3


Enter Coeff:2
Enter Pow:2

Continue adding more terms to the polynomial list?(Y = 1/N = 0): 1


Enter Coeff:5
Enter Pow:1

Continue adding more terms to the polynomial list?(Y = 1/N = 0): 1


Enter Coeff:3
Enter Pow:0

Continue adding more terms to the polynomial list?(Y = 1/N = 0): 0


Stored the 1st expression

The polynomial expression is:


4x^3 + 2x^2 + 5x^1 + 3x^0

Create 2nd expression


Enter Coeff:3
Enter Pow:3

Continue adding more terms to the polynomial list?(Y = 1/N = 0): 1


Enter Coeff:4
Enter Pow:2

Continue adding more terms to the polynomial list?(Y = 1/N = 0): 1


Enter Coeff:6
Enter Pow:1

Continue adding more terms to the polynomial list?(Y = 1/N = 0): 1


Enter Coeff:2
Enter Pow:0
Continue adding more terms to the polynomial list?(Y = 1/N = 0): 0

Stored the 2nd expression


The polynomial expression is:
3x^3 + 4x^2 + 6x^1 + 2x^0

Addition is completed
The polynomial expression is:
7x^3 + 6x^2 + 11x^1 + 5x^0

Add two more expressions? (Y = 1/N = 0): 0


RESULT:
Thus a C program for Polynomial using Linked List was implemented and executed
successfully.
EX.NO: 7(B) INFIX TO POSTFIX EXPRESSION

DATE:
AIM:
To write a C program for the conversion of Infix to Postfix using Stack.

ALGORITHM:
Step 1 : Start the program
Step 2 : Define a array stack of size max = 20
Step 3 : Initialize top = -1
Step 4 : Read the infix expression character-by-character and if the character is an operand print it
Step 5 : If character is an operator, compare the operator’s priority with the stack[top] operator. If the
stack [top] operator has higher or equal priority than the input operator, Pop it from the stack
and print it. Else, Push the input operator onto the stack.
Step 6 : If character is a left parenthesis, then push it onto the stack
Step 7: If the character is a right parenthesis, pop all the operators from the stack and print it until a left
parenthesis is encountered. Do not print the parenthesis.
Step 8: Stop the program.

PROGRAM:
#include <stdio.h>
#include <conio.h>
#include <string.h>
#define MAX 20

int top = -1;

char stack[MAX];
char pop();
void push(char item);

int prcd(char symbol)

{
switch(symbol)
{
case '+':
case '-':
return 2;
break;
case '*':
case '/':
return 4;
break;
case '^':
case '$':
return 6;
break;
case '(':
case ')':
case '#':
return 1;
break;
}
}

int isoperator(char symbol)


{
switch(symbol)
{
case '+':
case '-':
case '*':
case '/':
case '^':
case '$':
case '(':
case ')':
return 1;
break;

default:
return 0;
}
}

void convertip(char infix[],char postfix[])

{
int i,symbol,j = 0;
stack[++top] = '#';
for(i=0;i<strlen(infix);i++)
{
symbol = infix[i];
if(isoperator(symbol) == 0)
{
postfix[j] = symbol;
j++;
}
else
{
if(symbol == '(')
push(symbol);
else if(symbol == ')')
{
while(stack[top] != '(')
{
postfix[j] = pop();
j++;
}
pop(); //pop out (.
}
else
{
if(prcd(symbol) > prcd(stack[top]))
push(symbol);
else
{
while(prcd(symbol) <= prcd(stack[top]))
{
postfix[j] = pop();
j++;
}
push(symbol);
}
}
}

while(stack[top] != '#')

{
postfix[j] = pop();
j++;

}
postfix[j] = '\0';
}

main()
{
char infix[20],postfix[20];
clrscr();
printf("Enter the valid infix string: ");
gets(infix);
convertip(infix, postfix);
printf("The corresponding postfix string is:");
puts(postfix);
getch();
}

void push(char item)


{
top++;
stack[top] = item;

char pop()
{
char a;
a = stack[top];
top--;
return a;

OUTPUT:
Enter the valid infix string:
(A+B)*C+ (D-A)
The corresponding postfix string is:
AB+C*DA-+

RESULT:
Thus the conversion of Infix to Postfix using Stack was implemented and executed
successfully.
EX.NO: 7(C)
EVALUATION OF POSTFIX EXPRESSION
DATE:
AIM:
To write a C program for the evaluation of Postfix expression using Stack.

ALGORITHM:
Step 1 : Start the program
Step 2 : Define a array stack of SIZE as 50
Step 3 : Scan the Postfix string from left to right.
Step 4 : If the scanned character is an operand, add it to the stack. If the scanned character is
an operator, there will be at least two operands in the stack.
Step 5 : If the scanned character is an Operator, then we store the top most element of the
stack (topStack) in a variable temp. Pop the stack. Now evaluate topStack
(Operator)temp. Pop the stack and Push result into the stack.
Step 6 : Repeat this step till all the characters are scanned.
Step 7: After all characters are scanned, we will have only one element in the stack. Return
topStack.
Step 8: Stop the program.

PROGRAM:
#define SIZE 50
#include <ctype.h>
int s[SIZE];
int top=-1;
void push(int elem)
{
s[++top]=elem;
}

int pop()
{
return(s[top--]);
}

void main()
{
char pofx[50],ch;
int i=0,op1,op2;
printf("<-----Stack Application: Evaluating Postfix Expression----->\n");
printf("\n\nEnter the Postfix Expression:");
scanf("%s",pofx);

while( (ch=pofx[i++]) != '\0')


{
if(isdigit(ch)) push(ch-'0');
else
{
op2=pop();
op1=pop();
switch(ch)
{
case '+':push(op1+op2);break;
case '-':push(op1-op2);break;
case '*':push(op1*op2);break;
case '/':push(op1/op2);break;
}
}
}
printf("\n Given Postfix Expression: %s\n",pofx);

printf("\n Result after Evaluation: %d\n",s[top]);


}

OUTPUT:
<-----Stack Application: Evaluating Postfix Expression----->
Enter the Postfix Expression: 245*+
Given Postfix Expression: 245*+
Result after Evaluation: 22

RESULT:
Thus the evaluation of Postfix expression using Stack was implemented and executed
successfully.
EX. NO: 7(D) PRIORITY QUEUE
DATE:
AIM:
To write a C program for the implementation of Priority Queue using Queues.

ALGORITHM:
Step 1 : Start the program
Step 2 : Declare the required functions to implement the operations of Prority Queue.
Step 3 : Insert the elements to the Priority Queue using insert( )
Step 4 : Delete the elements from the Priority Queue using del( )
Step 5 : Print the elements in the list by using display( )
Step 6 : Stop the program

PROGRAM:
# include <stdio.h>
# include <conio.h>
void insert();
void del();
void display();
struct node
{
int priority;
int info;
struct node *link;
}*front = NULL;

main()
{
int choice;
clrscr();
printf("\n\n PRIORITY QUEUE USING LINKED LIST \n\n");
while(1)
{
printf("\n\n--------------------------- MAIN MENU -------------------------------------\n\n");
printf("1.Insert.\n\n");
printf("2.Delete.\n\n");
printf("3.Display.\n\n");
printf("4.Quit.\n\n");
printf("Enter your choice : ");
scanf("%d", &choice);
switch(choice)
{
case 1:
insert();
break;
case 2:
del();
break;
case 3:
display();
break;
case 4:
exit(1);
default :
printf("INVALID CHOICE TRY AGAIN!!!!!!1\n");
}
}
}

void insert()
{
struct node *tmp,*q;
int added_item,item_priority;
tmp = (struct node *)malloc(sizeof(struct node));
printf("\n------------------------------------------------------------------------------\n");
printf("\nInput the data to be added in the queue : ");
scanf("%d",&added_item);
printf("\n\nEnter its priority : ");
scanf("%d",&item_priority);
printf("\n\n------------------------------------------------------------------------------\n");
tmp  info = added_item;
tmp  priority = item_priority;
if( front == NULL || item_priority < front  priority )
{
tmp  link = front;
front = tmp;
}
else
{
q = front;
while( q  link != NULL && q  link  priority <= item_priority )

q=q  link;
tmp  link = q  link;
q  link = tmp;
}
}
void del()
{
struct node *tmp;
if(front == NULL)
{
printf("\n--------------------------------------------------------------------");
printf("\n\nQueue Underflow\n");
printf("\n------------------------------------------------------------------------");
}
else
{
tmp = front;
printf("\n----------------------------------------------------------------------------\n");
printf("\n\nDeleted data is %d\n",tmp  info);
printf("\n-----------------------------------------------------------------------------\n\n");
front = front  link;
free(tmp);
}
}

void display()
{
struct node *ptr;
ptr = front;
if(front == NULL)
{
printf("\n-----------------------------------------------------------------------");
printf("\n\nQueue is empty\n");
printf("\n--------------------------------------------------------------------------");
}
else
{
printf("\n\n---------------------- Queue --------------------------------\n\n");
printf("Priority\tData\n\n");
while(ptr != NULL)
{
printf("%d \t\t%d\n\n",ptr  priority,ptr  info);
ptr = ptr  link;
}
}
}

OUTPUT:
PRIORITY QUEUE USING LINKED LIST

--------------------------- MAIN MENU -------------------------------------

1.Insert.

2.Delete.

3.Display.

4.Quit.

Enter your choice : 1

------------------------------------------------------------------------------

Input the data to be added in the queue : 23

Enter its priority : 2


------------------------------------------------------------------------------

--------------------------- MAIN MENU -------------------------------------


1.Insert.

2.Delete.

3.Display.

4.Quit.

Enter your choice : 1

------------------------------------------------------------------------------
Input the data to be added in the queue : 24

Enter its priority : 1

------------------------------------------------------------------------------
--------------------------- MAIN MENU -------------------------------------
1.Insert.

2.Delete.

3.Display.

4.Quit.
Enter your choice : 3

---------------------- Queue --------------------------------

Priority Data

1 24

2 23

--------------------------- MAIN MENU -------------------------------------


1.Insert.

2.Delete.

3.Display.

4.Quit.

Enter your choice : 2


----------------------------------------------------------------------------
Deleted data is 24
-----------------------------------------------------------------------------

--------------------------- MAIN MENU -------------------------------------

1.Insert.

2.Delete.
3.Display.

4.Quit.

Enter your choice : 4

RESULT:
Thus a C program for Priority Queue was implemented and executed successfully.
EX. NO: 8 BINARY SEARCH TREE

DATE:
AIM:
To write a C program for the implementation of Binary Search Tree.

ALGORITHM:
Step 1 : Start the program
Step 2 : Create the nodes and fill the given data using CreateNode( )
Step 3 : Insert a new node into the tree using insertion( ). If the element to be inserted is less
than the element present in the root node, traverse the left sub-tree recursively until we
reach T->left/T->right is NULL and place the new node at T->left/T->right. If the
element to be inserted is greater than the element present in root node, traverse the
right sub-tree recursively until we reach T->left/T->right is NULL and place the new
node at T->left/T->right.
Step 4 : Delete a node from the tree using deletion( ) and deletes the nodes according to the
cases of deletion
Step 5 : Search the element in the tree using findElement( )
Step 6 : Print the nodes in the tree using inorder traversal by using traverse( )
Step 7 : Stop the program

PROGRAM:
#include <stdio.h>
#include <stdlib.h>

struct treeNode {
int data;
struct treeNode *left, *right;
};

struct treeNode *root = NULL;

/* create a new node with the given data */


struct treeNode* createNode(int data) {
struct treeNode *newNode;
newNode = (struct treeNode *) malloc(sizeof (struct treeNode));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return(newNode);
}
/* insertion in binary search tree */
void insertion(struct treeNode **node, int data) {
if (*node == NULL) {
*node = createNode(data);
} else if (data < (*node)->data) {
insertion(&(*node)->left, data);
} else if (data > (*node)->data) {
insertion(&(*node)->right, data);
}
}

/* deletion in binary search tree */


void deletion(struct treeNode **node, struct treeNode **parent, int data) {
struct treeNode *tmpNode, *tmpParent;
if (*node == NULL)
return;
if ((*node)->data == data) {
/* deleting the leaf node */
if (!(*node)->left && !(*node)->right) {
if (parent) {
/* delete leaf node */
if ((*parent)->left == *node)
(*parent)->left = NULL;
else
(*parent)->right = NULL;
free(*node);
} else {
/* delete root node with no children */
free(*node);
}
/* deleting node with one child */
} else if (!(*node)->right && (*node)->left) {
/* deleting node with left child alone */
tmpNode = *node;
(*parent)->right = (*node)->left;
free(tmpNode);
*node = (*parent)->right;
} else if ((*node)->right && !(*node)->left) {
/* deleting node with right child alone */
tmpNode = *node;
(*parent)->left = (*node)->right;
free(tmpNode);
(*node) = (*parent)->left;
} else if (!(*node)->right->left) {

tmpNode = *node;

(*node)->right->left = (*node)->left;

(*parent)->left = (*node)->right;
free(tmpNode);
*node = (*parent)->left;
} else {
tmpNode = (*node)->right;
while (tmpNode->left) {
tmpParent = tmpNode;
tmpNode = tmpNode->left;
}
tmpParent->left = tmpNode->right;
tmpNode->left = (*node)->left;
tmpNode->right =(*node)->right;
free(*node);
*node = tmpNode;
}
} else if (data < (*node)->data) {
/* traverse towards left subtree */
deletion(&(*node)->left, node, data);
} else if (data > (*node)->data) {
/* traversing towards right subtree */
deletion(&(*node)->right, node, data);
}
}

/* search the given element in binary search tree */


void findElement(struct treeNode *node, int data) {
if (!node)
return;
else if (data < node->data) {
findElement(node->left, data);
} else if (data > node->data) {
findElement(node->right, data);
} else
printf("data found: %d\n", node->data);
return;

}
void traverse(struct treeNode *node) {
if (node != NULL) {
traverse(node->left);
printf("%3d", node->data);
traverse(node->right);
}
return;
}

int main() {
int data, ch;
while (1) {
printf("\n********************************\n");
printf("1. Insertion in Binary Search Tree\n");
printf("2. Deletion in Binary Search Tree\n");
printf("3. Search Element in Binary Search Tree\n");
printf("4. Inorder traversal\n5. Exit\n");
printf("\n********************************\n");
printf("Enter your choice:");
scanf("%d", &ch);
switch (ch) {
case 1:
while (1) {
printf("Enter your data:");
scanf("%d", &data);
insertion(&root, data);
printf("Continue Insertion(0/1):");
scanf("%d", &ch);
if (!ch)
break;
}
break;
case 2:
printf("Enter your data:");
scanf("%d", &data);
deletion(&root, NULL, data);
break;
case 3:
printf("Enter value for data:");
scanf("%d", &data);
findElement(root, data);
break;
case 4:
printf("Inorder Traversal:\n");
traverse(root);
printf("\n");
break;
case 5:
exit(0);
default:
printf("u've entered wrong option\n");
break;
}
}
return 0;

OUTPUT:
********************************
1. Insertion in Binary Search Tree
2. Deletion in Binary Search Tree
3. Search Element in Binary Search Tree
4. Inorder traversal
5. Exit
********************************
Enter your choice:1
Enter your data:20
Continue Insertion(0/1):1
Enter your data:14
Continue Insertion(0/1):1
Enter your data:9
Continue Insertion(0/1):1
Enter your data:19
Continue Insertion(0/1):1
Enter your data:25
Continue Insertion(0/1):1
Enter your data:21
Continue Insertion(0/1):1
Enter your data:23
Continue Insertion(0/1):1
Enter your data:30
Continue Insertion(0/1):1
Enter your data:26
Continue Insertion(0/1):0
********************************
1. Insertion in Binary Search Tree
2. Deletion in Binary Search Tree
3. Search Element in Binary Search Tree
4. Inorder traversal
5. Exit
********************************
Enter your choice:4
Inorder Traversal:
9 14 19 20 21 23 25 26 30
********************************
1. Insertion in Binary Search Tree
2. Deletion in Binary Search Tree
3. Search Element in Binary Search Tree
4. Inorder traversal
5. Exit
********************************
Enter your choice:2
Enter your data:9
********************************
1. Insertion in Binary Search Tree
2. Deletion in Binary Search Tree
3. Search Element in Binary Search Tree
4. Inorder traversal
5. Exit
********************************
Enter your choice:4
Inorder Traversal:
14 19 20 21 23 25 26 30
********************************
1. Insertion in Binary Search Tree
2. Deletion in Binary Search Tree
3. Search Element in Binary Search Tree
4. Inorder traversal
5. Exit
********************************
Enter your choice:2
Enter your data:14
********************************
1. Insertion in Binary Search Tree
2. Deletion in Binary Search Tree
3. Search Element in Binary Search Tree
4. Inorder traversal
5. Exit
********************************
Enter your choice: 4
Inorder Traversal:
19 20 21 23 25 26 30
********************************
1. Insertion in Binary Search Tree
2. Deletion in Binary Search Tree
3. Search Element in Binary Search Tree
4. Inorder traversal
5. Exit
********************************
Enter your choice:2
Enter your data:30
********************************
1. Insertion in Binary Search Tree
2. Deletion in Binary Search Tree
3. Search Element in Binary Search Tree
4. Inorder traversal
5. Exit
********************************
Enter your choice:4
Inorder Traversal:
19 20 21 23 25 26
********************************
1. Insertion in Binary Search Tree
2. Deletion in Binary Search Tree
3. Search Element in Binary Search Tree
4. Inorder traversal
5. Exit
********************************
Enter your choice:2
Enter your data:20
********************************
1. Insertion in Binary Search Tree
2. Deletion in Binary Search Tree
3. Search Element in Binary Search Tree
4. Inorder traversal
5. Exit
********************************
Enter your choice:4
Inorder Traversal:
19 21 23 25 26
********************************
1. Insertion in Binary Search Tree
2. Deletion in Binary Search Tree
3. Search Element in Binary Search Tree
4. Inorder traversal
5. Exit
********************************
Enter your choice:1
Enter your data:15
Continue Insertion(0/1):1
Enter your data:14
Continue Insertion(0/1):1
Enter your data:16
Continue Insertion(0/1):1
Enter your data:17
Continue Insertion(0/1):0
********************************
1. Insertion in Binary Search Tree
2. Deletion in Binary Search Tree
3. Search Element in Binary Search Tree
4. Inorder traversal
5. Exit
********************************
Enter your choice:4
Inorder Traversal:
14 15 16 17 19 21 23 25 26
********************************
1. Insertion in Binary Search Tree
2. Deletion in Binary Search Tree
3. Search Element in Binary Search Tree
4. Inorder traversal
5. Exit
********************************
Enter your choice:3
Enter value for data:21
data found: 21
********************************
1. Insertion in Binary Search Tree
2. Deletion in Binary Search Tree
3. Search Element in Binary Search Tree
4. Inorder traversal
5. Exit
********************************
Enter your choice:5

RESULT:
Thus a C program for Binary Search Tree was implemented and executed
successfully.
EX. NO:9 AVL TREES

DATE:
AIM:
To write a C program for the implementation of AVL Tree.

ALGORITHM:
Step 1 : Start the program
Step 2 : Declare the required functions to implement the operations of AVL Trees.
Step 3 : Insert a new node into the tree using insert( )
Step 4 : In order tree traversal can be obtained using inorder( )
Step 5 : Pre order tree traversal can be obtained using preorder( )
Step 6 : Post order tree traversal can be obtained using postorder( )
Step 7 : Delete the nodes from the tree using Delete( )
Step 8: Rotating the tree to make it balanced can be done using BF( ), RR( ), LL( ), LR( ) and
RL( ) respectively
Step 9: Stop the program

PROGRAM:
#include<stdio.h>

typedef struct node


{
int data;
struct node *left,*right;
int ht;
}node;

node *insert(node *,int);


node *Delete(node *,int);
void preorder(node *);
void inorder(node *);
void postorder(node *);
int height( node *);
node *rotateright(node *);
node *rotateleft(node *);
node *RR(node *);
node *LL(node *);
node *LR(node *);
node *RL(node *);
int BF(node *);

int main()
{
node *root=NULL;
int x,n,i,op;

do
{
printf("\n********************");
printf("\n1)Create");
printf("\n2)Insert");
printf("\n3)Delete");
printf("\n4)Print");
printf("\n5)Exit");
printf("\n********************");
printf("\nEnter Your Choice:");
scanf("%d",&op);

switch(op)
{
case 1: printf("\nEnter no. of elements:");
scanf("%d",&n);
printf("\nEnter tree data:");
root=NULL;
for(i=0;i<n;i++)
{
scanf("%d",&x);
root=insert(root,x);
}
break;

case 2: printf("\nEnter a data:");


scanf("%d",&x);
root=insert(root,x);
break;

case 3: printf("\nEnter a data:");


scanf("%d",&x);
root=Delete(root,x);
break;

case 4: printf("\nPreorder sequence:\n");


preorder(root);
printf("\n\nInorder sequence:\n");
inorder(root);
printf("\n\nPostorder sequence:\n");
postorder(root);
printf("\n");
break;
}
}while(op!=5);

return 0;
}

node * insert(node *T,int x)


{
if(T==NULL)
{
T=(node*)malloc(sizeof(node));
T->data=x;
T->left=NULL;
T->right=NULL;
}
else
if(x > T->data) // insert in right subtree
{
T->right=insert(T->right,x);
if(BF(T)==-2)
if(x>T->right->data)
T=RR(T);
else
T=RL(T);
}
else
if(x<T->data)
{
T->left=insert(T->left,x);
if(BF(T)==2)
if(x < T->left->data)
T=LL(T);
else
T=LR(T);
}

T->ht=height(T);

return(T);
}
node * Delete(node *T,int x)
{
node *p;

if(T==NULL)
{
return NULL;
}
else
if(x > T->data) // insert in right subtree
{
T->right=Delete(T->right,x);
if(BF(T)==2)
if(BF(T->left)>=0)
T=LL(T);
else
T=LR(T);
}
else
if(x<T->data)
{
T->left=Delete(T->left,x);
if(BF(T)==-2) //Rebalance during windup
if(BF(T->right)<=0)
T=RR(T);
else
T=RL(T);
}
else
{
//data to be deleted is found
if(T->right!=NULL)
{ //delete its inorder succesor
p=T->right;

while(p->left!= NULL)
p=p->left;

T->data=p->data;
T->right=Delete(T->right,p->data);

if(BF(T)==2)//Rebalance during windup


if(BF(T->left)>=0)
T=LL(T);
else
T=LR(T);\
}
else
return(T->left);
}
T->ht=height(T);
return(T);
}

int height(node *T)


{
int lh,rh;
if(T==NULL)
return(0);

if(T->left==NULL)
lh=0;
else
lh=1+T->left->ht;

if(T->right==NULL)
rh=0;
else
rh=1+T->right->ht;

if(lh>rh)
return(lh);

return(rh);
}

node * rotateright(node *x)


{
node *y;
y=x->left;
x->left=y->right;
y->right=x;
x->ht=height(x);
y->ht=height(y);
return(y);
}

node * rotateleft(node *x)


{
node *y;
y=x->right;
x->right=y->left;
y->left=x;
x->ht=height(x);
y->ht=height(y);

return(y);
}

node * RR(node *T)


{
T=rotateleft(T);
return(T);
}

node * LL(node *T)


{
T=rotateright(T);
return(T);
}

node * LR(node *T)


{
T->left=rotateleft(T->left);
T=rotateright(T);

return(T);
}

node * RL(node *T)


{
T->right=rotateright(T->right);
T=rotateleft(T);
return(T);
}

int BF(node *T)


{
int lh,rh;
if(T==NULL)
return(0);

if(T->left==NULL)
lh=0;
else
lh=1+T->left->ht;

if(T->right==NULL)
rh=0;
else
rh=1+T->right->ht;

return(lh-rh);
}

void preorder(node *T)


{
if(T!=NULL)
{
printf("%d(Bf=%d)\t",T->data,BF(T));
preorder(T->left);
preorder(T->right);
}
}
void postorder(node *T)
{
if(T!=NULL)
{
postorder(T->left);
postorder(T->right);
printf("%d(Bf=%d)\t",T->data,BF(T));
}
}

void inorder(node *T)


{
if(T!=NULL)
{
inorder(T->left);
printf("%d(Bf=%d)\t",T->data,BF(T));
inorder(T->right);
}
}

OUTPUT:
********************
1)Create
2)Insert
3)Delete
4)Print
5)Exit
********************
Enter Your Choice:1

Enter no. of elements:5

Enter tree data:7


12
4
8
5
********************
1)Create
2)Insert
3)Delete
4)Print
5)Exit
********************
Enter Your Choice:4

Preorder sequence:
7(Bf=0)4(Bf=-1)5(Bf=0)12(Bf=1)8(Bf=0)

Inorder sequence:
4(Bf=-1)5(Bf=0)7(Bf=0)8(Bf=0)12(Bf=1)

Postorder sequence:
5(Bf=0)4(Bf=-1)8(Bf=0)12(Bf=1)7(Bf=0)

********************
1)Create
2)Insert
3)Delete
4)Print
5)Exit
********************
Enter Your Choice: 3
Enter a data:8
********************
1)Create
2)Insert
3)Delete
4)Print
5)Exit
********************
Enter Your Choice:4

Preorder sequence:
7(Bf=1)4(Bf=-1)5(Bf=0)12(Bf=0)

Inorder sequence:
4(Bf=-1)5(Bf=0)7(Bf=1)12(Bf=0)

Postorder sequence:
5(Bf=0)4(Bf=-1)12(Bf=0)7(Bf=1)

********************
1)Create
2)Insert
3)Delete
4)Print
5)Exit
********************
Enter Your Choice:5

RESULT:
Thus a C program for AVL Tree was implemented and executed successfully.
EX. NO:10 PRIORITY QUEUE USING HEAP
DATE:
AIM:
To write a C program for the implementation of Priority Queue using Heap.

ALGORITHM:
Step 1 : Start the program
Step 2 : Define the Heapsize as 100
Step 3 : Insert the element into the Heap using insertHeap( ).
Step 4 : Delete the elements from the Heap using deleteNode( )
Step 5 : If parent of the current node has value greater than its child, then swap parent and child
nodes. Traverse up the tree until you hit a condition where parent node is having lesser
value than children using buildup( )
Step 6 : Replace the root node with value by using replaceNode( )
Step 7 : Print the elements in the Heap by using display( )
Step 8: Stop the program

PROGRAM:
#include <stdio.h>
#include <stdlib.h>

#define HEAPCOUNT 100

int count = 0;

void insertHeap(int *data, int low, int count) {


int pos = (2 * low) + 1, current = data[low];
while (pos <= count) {
if (pos < count && data[pos] >data[pos + 1])
pos++;
if (current <= data[pos])
break;
else {
data[low] = data[pos];
low = pos;
pos = (2 * low) + 1;
}
}
data[low] = current;
return;
}

void buildHeap(int *data, int n) {


int low;
for (low = n/2 - 1; low >= 0; low--) {
insertHeap(data, low, n-1);
}
return;
}

void buildUp(int *data, int index) {


int val = data[index];
while (data[(index - 1) / 2] >= val) {
data[index] = data[(index - 1) / 2];
if (!index)
break;
index = (index - 1) / 2;
}
data[index] = val;
return;
}

/* adding new node to the binary heap */


void addNode(int *data, int val, int n) {
data[n] = val;
buildUp(data, n);
return;
}

/* delete a node from binary heap */


void deleteNode(int *data, int n) {
int val = data[0];
data[0] = data[n];
insertHeap(data, 0, n - 1);
printf("%d is deleted from the heap\n", val);
return;
}

/* replacing root node with value val */


void replaceNode(int *data, int val, int n) {
int i;
data[0] = val;
for (i = n/2 - 1; i >= 0; i--)
insertHeap(data, i, n - 1);
return;
}

void display(int *data, int n) {


int i;
printf("\nData in Binary Heap:\n");
for (i = 0; i <= n; i++) {
printf("%d ", data[i]);
}
printf("\n\n");
}

int main() {
int n, i, *data, temp, ch, val;
data = (int *)malloc(sizeof(int) * HEAPCOUNT);
printf("Enter the no of elements(1-80):");
scanf("%d", &n);

if (n < 1 || n > 80) {


printf("Threshold Exceeded!!\n");
return 0;
}
for (i = 0; i < n; i++) {
printf("Input %d:", i + 1);
scanf("%d", &data[i]);
count++;
}

buildHeap(data, n);
while (n < (HEAPCOUNT -1)) {
printf(“***************************\n”);
printf("1. Add New Node\N2. Delete Node\n");
printf("3. Replace Node\N4. Display Heap\n5. Exit \n");
printf(“***************************\n”);
printf("\nEnter your choice:");
scanf("%d", &ch);

switch(ch) {
case 1:
printf("Enter your input:");
scanf("%d", &val);
addNode(data, val, n);
n++;
break;
case 2:
deleteNode(data, n -1);
n--;
break;
case 3:
printf("Enter input value:");
scanf("%d", &val);
replaceNode(data, val, n);
break;
case 4:
display(data, n - 1);
break;
case 5:
goto sort;

default:
printf("Wrong Option!!\n");
break;
}

}
sort:
for (i = n - 1; i > 0; i--) {
temp = data[i];
data[i] = data[0];
data[0] = temp;
insertHeap(data, 0, i - 1);
}
printf("Sorted Data:\n");
for (i = 0; i < n; i++)
printf("%d ", data[i]);
printf("\n");
return 0;
}

OUTPUT:
Enter the no of elements(1-80):6
Input 1:90
Input 2:25
Input 3:30
Input 4:15
Input 5:7
Input 6:19
***************************
1. Add New Node
2. Delete Node
3. Replace Node
4. Display Heap
5. Exit
***************************
Enter your choice:1
Enter your input:12

***************************
1. Add New Node
2. Delete Node
3. Replace Node
4. Display Heap
5. Exit
***************************
Enter your choice:3
Enter input value:17

***************************
1. Add New Node
2. Delete Node
3. Replace Node
4. Display Heap
5. Exit
***************************
Enter your choice:4

Data in Binary Heap:


12 15 17 90 25 30 19
***************************
1. Add New Node
2. Delete Node
3. Replace Node
4. Display Heap
5. Exit
***************************
Enter your choice:5

Sorted Data:
90 30 25 19 17 15 12

RESULT:
Thus a C program for Prority Queue was implemented and executed
successfully.
EX. NO: 11 (A) GRAPH REPRESENTATIONS
DATE:
AIM:
To write a C program for the implementation of Adjacency matrix and List.

ALGORITHM:
Step 1 : Start the program
Step 2 : Declare the required functions to implement the operations of Adjacency matrix and
List
Step 3 : Structures are declared to define Graph, Adjacent node, List and Matrix.
Step 4 : Insert a new edge into the tree using addEdge()
Step 5 : Adjacent list of a undirected graph is obtained using adjlist()
Step 6 : Adjacent Matrix of a undirected graph is obtained using adjmatrix()
Step 7 : Display the undirected graph using printGraph()
Step 8: Stop the program

PROGRAM:
#include<stdio.h>
void adjmatrix();
void adjlist();
int a[20][20];
int n,i,s,ch,j;
struct AdjListNode
{
int dest;
struct AdjListNode* next;
};

// A structure to represent an adjacency list


struct AdjList
{
struct AdjListNode *head;
};

// A structure to represent a graph. A graph


// is an array of adjacency lists.
// Size of array will be V (number of vertices
// in graph)
struct Graph
{
int V;
struct AdjList* array;
};

// A utility function to create a new adjacency list node


struct AdjListNode* newAdjListNode(int dest)
{
struct AdjListNode* newNode =
(struct AdjListNode*) malloc(sizeof(struct AdjListNode));
newNode->dest = dest;
newNode->next = NULL;
return newNode;
}

// A utility function that creates a graph of V vertices


struct Graph* createGraph(int V)
{
struct Graph* graph =
(struct Graph*) malloc(sizeof(struct Graph));
graph->V = V;

// Create an array of adjacency lists. Size of


// array will be V
graph->array =
(struct AdjList*) malloc(V * sizeof(struct AdjList));

// Initialize each adjacency list as empty by


// making head as NULL
int i;
for (i = 0; i < V; ++i)
graph->array[i].head = NULL;

return graph;
}

// Adds an edge to an undirected graph


void addEdge(struct Graph* graph, int src, int dest)
{
// Add an edge from src to dest. A new node is
// added to the adjacency list of src. The node
// is added at the begining
struct AdjListNode* newNode = newAdjListNode(dest);
newNode->next = graph->array[src].head;
graph->array[src].head = newNode;

// Since graph is undirected, add an edge from


// dest to src also
newNode = newAdjListNode(src);
newNode->next = graph->array[dest].head;
graph->array[dest].head = newNode;
}

// A utility function to print the adjacency list


// representation of graph
void printGraph(struct Graph* graph)
{
int v;
for (v = 0; v < graph->V; ++v)
{
struct AdjListNode* pCrawl = graph->array[v].head;
printf("\n Adjacency list of vertex %d\n head ", v);
while (pCrawl)
{
printf("-> %d", pCrawl->dest);
pCrawl = pCrawl->next;
}
printf("\n");
}
}

void adjmatrix()
{
printf("\nEnter the number of vertices:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("\nEnter 1 if %d has a Node with %d Else 0:",i,j);
scanf("%d",&a[i][j]);
}
}
printf("\nAdjacency Matrix is:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf(" %d",a[i][j]);
}
printf("\n");
}
}
void adjlist()
{
// int V = 5;
int V;
printf("\nEnter the number of vertices:");
scanf("%d",&V);
int src, dest, noofedges;
struct Graph* graph = createGraph(V);
printf("\n Enter the number of edges that are to be added:");
scanf("%d",&noofedges);
for(int i=1;i<=noofedges;i++)
{
printf("\n Enter the source and destination to add the edges:");
scanf("%d %d",&src,&dest);
addEdge(graph,src,dest);
}

printGraph(graph);
}

void main()
{

char c,dummy;

do
{
printf("\n*************************");
printf("\n**********MENU*********");
printf("\n*************************");
printf("\n1.Adjacency Matrix");
printf("\n2.Adjacency List");
printf("\nEnter your choice:");
scanf("%d",&ch);

switch(ch)
{
case 1:
adjmatrix();
break;
case 2:
adjlist();
break;
}
printf("\nDo you want to continue(Y/N)?:");
scanf("%c",&dummy);
scanf("%c",&c);
}while((c=='y')||(c=='Y'));
}//End of main
OUTPUT:
*************************
**********MENU*********
*************************
1.Adjacency Matrix
2.Adjacency List
Enter your choice:1
Enter the number of vertices:3

Enter 1 if 1 has a Node with 1 Else 0:1

Enter 1 if 1 has a Node with 2 Else 0:1

Enter 1 if 1 has a Node with 3 Else 0:0

Enter 1 if 2 has a Node with 1 Else 0:1

Enter 1 if 2 has a Node with 2 Else 0:0

Enter 1 if 2 has a Node with 3 Else 0:1

Enter 1 if 3 has a Node with 1 Else 0:0

Enter 1 if 3 has a Node with 2 Else 0:1

Enter 1 if 3 has a Node with 3 Else 0:1

Adjacency Matrix is:


110
101
011

Do you want to continue(Y/N)?:Y


*************************
**********MENU*********
*************************
1.Adjacency Matrix
2.Adjacency List
Enter your choice:2

Enter the number of edges that are to be added:7

Enter the source and destination to add the edges:0 1

Enter the source and destination to add the edges:0 4

Enter the source and destination to add the edges:1 2


Enter the source and destination to add the edges:1 3

Enter the source and destination to add the edges:1 4

Enter the source and destination to add the edges:2 3

Enter the source and destination to add the edges:2 4

Adjacency list of vertex 0


head -> 4-> 1

Adjacency list of vertex 1


head -> 4-> 3-> 2-> 0

Adjacency list of vertex 2


head -> 4-> 3-> 1

Adjacency list of vertex 3


head -> 2-> 1

Adjacency list of vertex 4


head -> 2-> 1-> 0

Do you want to continue(Y/N)?:N

RESULT:
Thus the C program for representation of graph was implement ed and executed
successfully.
EX. NO: 11 (B) GRAPH TRAVERSALS
DATE:

AIM:
To write a C program for the implementation of Graph Traversal using BFS and DFS.

ALGORITHM:
Step 1 : Start the program
Step 2 : Vi is visited and then all vertices adjacent to Vi are traversed recursively using
DFS/BFS
Step 3 : For DFS,Since, a graph can have cycles. We must avoid revisiting a node. To do
this,when we visit a vertex V,we mark it visited.
For BFS,avoid revisiting a node. To do this, when we visit a vertex V,we mark it
visited.
Step 4 : A node that has already been marked as visited should not be selected for traversal.
Step 5 : Marking of visited vertices can be done with the help of a global array visited [].
Step 6 : Array visited [ ] is initialized to false.
Step 7: Stop the program

PROGRAM:
#include<stdio.h>
int q[20],top=-1,front=-1,rear=-1,a[20][20],vis[20],stack[20];
int delete();
void add(int item);
void bfs(int s,int n);
void dfs(int s,int n);
void push(int item);
int pop();

void main()
{
int n,i,s,ch,j;
char c,dummy;
printf("\nEnter the number of vertices:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("\nEnter 1 if %d has a Node with %d Else 0:",i,j);
scanf("%d",&a[i][j]);
}
}
printf("\nAdjacency Matrix is:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf(" %d",a[i][j]);
}
printf("\n");
}

do
{
for(i=1;i<=n;i++)
vis[i]=0;
printf("\n*************************");
printf("\n**********MENU*********");
printf("\n*************************");
printf("\n1.Breadth First Search");
printf("\n2.Depth First Search");
printf("\nEnter your choice:");
scanf("%d",&ch);
printf("\nEnter the source vertex:");
scanf("%d",&s);

switch(ch)
{
case 1:
bfs(s,n);
break;
case 2:
dfs(s,n);
break;
}
printf("\nDo you want to continue(Y/N)?:");
scanf("%c",&dummy);
scanf("%c",&c);
}while((c=='y')||(c=='Y'));
}//End of main

//**************BFS(breadth-first search) code**************//


void bfs(int s,int n)
{
int p,i;
add(s);
vis[s]=1;
p=delete();
if(p!=0)
printf(" %d",p);
while(p!=0)
{
for(i=1;i<=n;i++)
if((a[p][i]!=0)&&(vis[i]==0))
{
add(i);
vis[i]=1;
}
p=delete();
if(p!=0)
printf(" %d ",p);
}

for(i=1;i<=n;i++)
if(vis[i]==0)
bfs(i,n);
}

void add(int item)


{
if(rear==19)
printf("Queue Full");
else
{
if(rear==-1)
{
q[++rear]=item;
front++;
}
else
q[++rear]=item;
}
}
int delete()
{
int k;
if((front>rear)||(front==-1))
return(0);
else
{
k=q[front++];
return(k);
}
}

//***************DFS(depth-first search) code******************//


void dfs(int s,int n)
{
int i,k;
push(s);
vis[s]=1;
k=pop();
if(k!=0)
printf(" %d ",k);
while(k!=0)
{
for(i=1;i<=n;i++)
if((a[k][i]!=0)&&(vis[i]==0))
{
push(i);
vis[i]=1;
}
k=pop();
if(k!=0)
printf(" %d ",k);
}
for(i=1;i<=n;i++)
if(vis[i]==0)
dfs(i,n);
}

void push(int item)


{
if(top==19)
printf("Stack overflow ");
else
stack[++top]=item;
}
int pop()
{
int k;
if(top==-1)
return(0);
else
{
k=stack[top--];
return(k);
}
}

OUTPUT:
Enter the number of vertices:3

Enter 1 if 1 has a Node with 1 Else 0:1

Enter 1 if 1 has a Node with 2 Else 0:1

Enter 1 if 1 has a Node with 3 Else 0:0


Enter 1 if 2 has a Node with 1 Else 0:1

Enter 1 if 2 has a Node with 2 Else 0:0

Enter 1 if 2 has a Node with 3 Else 0:1

Enter 1 if 3 has a Node with 1 Else 0:0

Enter 1 if 3 has a Node with 2 Else 0:1


Enter 1 if 3 has a Node with 3 Else 0:0

Adjacency Matrix is:


110
101
010

*************************
**********MENU***********
*************************
1.Breadth First Search
2.Depth First Search
Enter your choice:1

Enter the source vertex:2


21 3
Do you want to continue(Y/N)?:Y
*************************
**********MENU***********
*************************
1.Breadth First Search
2.Depth First Search
Enter your choice:2

Enter the source vertex:1


1 2 3
Do you want to continue(Y/N)?:N

RESULT:
Thus a C program for Graph traversal Graph Traversal using BFS and DFS was
implemented and executed successfully.
EX. NO: 12 (A) SHORTEST PATH ALGORITHM - DIJKSTRA’S ALGORITHM
DATE:
AIM:
To write a C program for the implementation of shortest path using Dijkstra’s
algorithm.

ALGORITHM:
Step 1 : Start the program
Step 2 : Define the Infinity as 9999
Step 3 : Get the no. of nodes, adjacency matrix and the source node.
Step 4 : Find the cost required from source to all the other nodes using the algorithm by adding
it to the known nodes.
Step 5 : Print the distance and path from the source to all the other destinations
Step 6 : Stop the program

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

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

int main()
{
int G[MAX][MAX],i,j,n,u;
printf("Enter 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);
dijkstra(G,n,u);

return 0;
}

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


{

int cost[MAX][MAX],distance[MAX],pred[MAX];
int visited[MAX],count,mindistance,nextnode,i,j;

//pred[] stores the predecessor of each node


//count gives the number of nodes seen so far
//create the cost matrix
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];

//initialize pred[],distance[] and visited[]


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;

while(count<n-1)
{
mindistance=INFINITY;

//nextnode gives the node at minimum distance


for(i=0;i<n;i++)
if(distance[i]<mindistance&&!visited[i])
{
mindistance=distance[i];
nextnode=i;
}

//check if a better path exists through nextnode


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++;
}

//print the path and distance of each node


for(i=0;i<n;i++)
if(i!=startnode)
{
printf("\nDistance of node%d=%d",i,distance[i]);
printf("\nPath=%d",i);

j=i;
do
{
j=pred[j];
printf("<-%d",j);
}while(j!=startnode);
}
}
OUTPUT:
Enter no. of vertices:5

Enter the adjacency matrix:


0 10 0 30 0
10 0 12 30 2
12 11 0 21 0
13 18 14 0 9
17 18 19 15 0

Enter the starting node:1

Distance of node0=10
Path=0<-1
Distance of node2=12
Path=2<-1
Distance of node3=17
Path=3<-4<-1
Distance of node4=2
Path=4<-1

RESULT:
Thus a C program for finding the shortest path using Dijkstra’s algorithm was
implemented and executed successfully.
EX. NO: 12(B) SHORTEST PATH ALGORITHM - BELLMAN-FORD ALGORITHM
DATE:
AIM:
To write a C program for the implementation of shortest path using Bellman-Ford
algorithm.

ALGORITHM:
Step 1 : Start the program
Step 2 : Get the number of vertices, edges and the source.
Step 3 : Declare structures to represent the type of Edge and Graph
Step 4 : Create the graph using creatGraph( )
Step 5 : The shortest path of graph that contain V vertices, never contain "V-1" edges. So we do
here "V-1" relaxations and check for negative cycles using BellmanFord( )
Step 6 : Print the final distance from the source to destination using FinalSolution( )
Step 7 : Stop the program

PROGRAM:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>

struct Edge
{
int source, destination, weight;
};

struct Graph
{
int V, E;

struct Edge* edge;


};

struct Graph* createGraph(int V, int E)


{
struct Graph* graph = (struct Graph*) malloc( sizeof(struct Graph));

graph->V = V; //assigning values to structure elements that taken form user.

graph->E = E;
graph->edge = (struct Edge*) malloc( graph->E * sizeof( struct Edge ) );
return graph;
}

void FinalSolution(int dist[], int n)


{
printf("\nVertex\tDistance from Source Vertex\n");
int i;

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


printf("%d \t\t %d\n", i, dist[i]);
}
}

void BellmanFord(struct Graph* graph, int source)


{
int V = graph->V;

int E = graph->E;

int StoreDistance[V];

int i,j;

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


StoreDistance[i] = INT_MAX;

StoreDistance[source] = 0;

for (i = 1; i <= V-1; i++)


{
for (j = 0; j < E; j++)
{
int u = graph->edge[j].source;

int v = graph->edge[j].destination;

int weight = graph->edge[j].weight;

if (StoreDistance[u] + weight < StoreDistance[v])


StoreDistance[v] = StoreDistance[u] + weight;
}
}

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


{
int u = graph->edge[i].source;

int v = graph->edge[i].destination;

int weight = graph->edge[i].weight;

if (StoreDistance[u] + weight < StoreDistance[v])


printf("This graph contains negative edge cycle\n");
}

FinalSolution(StoreDistance, V);

return;
}

int main()
{
int V,E,S; //V = no.of Vertices, E = no.of Edges, S is source vertex

printf("Enter number of vertices in graph\n");


scanf("%d",&V);

printf("Enter number of edges in graph\n");


scanf("%d",&E);

printf("Enter your source vertex number\n");


scanf("%d",&S);

struct Graph* graph = createGraph(V, E);


int i;
for(i=0;i<E;i++){
printf("\nEnter edge %d properties Source, destination, weight respectively\n",i+1);
scanf("%d",&graph->edge[i].source);
scanf("%d",&graph->edge[i].destination);
scanf("%d",&graph->edge[i].weight);
}

BellmanFord(graph, S);
return 0;
}

OUTPUT:
Enter number of vertices in graph
5
Enter number of edges in graph
10
Enter your source vertex number
0
Enter edge 1 properties Source, destination, weight respectively
016
Enter edge 2 properties Source, destination, weight respectively
027
Enter edge 3 properties Source, destination, weight respectively
128
Enter edge 4 properties Source, destination, weight respectively
1 4 -4
Enter edge 5 properties Source, destination, weight respectively
135
Enter edge 6 properties Source, destination, weight respectively
3 1 -2
Enter edge 7 properties Source, destination, weight respectively
2 3 -3
Enter edge 8 properties Source, destination, weight respectively
249
Enter edge 9 properties Source, destination, weight respectively
402
Enter edge 10 properties Source, destination, weight respectively
437

Vertex Distance from Source Vertex


0 0
1 2
2 7
3 4
4 -2

RESULT:
Thus a C program for finding the shortest path using Bellman-Ford algorithm was
implemented and executed successfully.
EX. NO: 13(A) SEARCHIING
DATE:
AIM:
To write a C program to search the elementslinear search and binary search.

ALGORITHM:
Step 1 : Start the program
Step 2 : Read n numbers and search value.
Step 3 : Get the option from the user for Linear Search or Binary Search
Step 4 : If it is a binary search and check whether search value is equal to middle element, then
print value is found. If search value is less than middle element then search left half of
list with the same method. Else search right half of list with the same method.
Step 5: If it is a linear search, check whether search value is equal to first element then
print value is found. Else search with the second element and so on.
Step 6 : Stop the program.

PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
void main()
{
int a[100],i,n,item,s=0,ch,beg,end,mid;
clrscr();
printf("Enter No. of Elements:");
scanf("%d",&n);
printf("\nEnter Elements:\n");
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);

}
while(1)
{
printf("\n1.Linear Search\n2.Binary
Search\n3.Exit\n"); printf("Enter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("<-----LINEAR SEARCH----->\n");
printf("\nEnter Element you want to Search:");
scanf("%d",&item);
for(i=1;i<=n;i++)
{
if(a[i]==item)
{
printf("\nData is Found at Location : %d",i);
s=1;
break;
}
}
if(s==0)
{
printf("Data is Not Found");

}
break;
case 2:
printf("<-----BINARY SEARCH----->\n");
printf("\nEnter Item you want to Search:");
scanf("%d",&item);
beg=1;
end=n;
mid=(beg+end)/2;

while(beg<=end && a[mid]!=item)


{
if(a[mid]<item)
beg=mid+1;
else
end=mid-1;
mid=(beg+end)/2;
}
if(a[mid]==item)
{
printf("\nData is Found at Location : %d",mid);
}
else
{

printf("Data is Not Found");


}
break;
case 3:
default:
exit(0);
}
}
getch();
}
OUTPUT:
Enter No. of Elements:
5

Enter Elements:
2
4
3
5
1
1.Linear Search
2.Binary Search
3.Exit
Enter your choice:
1
<-----LINEAR SEARCH----->
Enter Element you want to Search:
1
Data is Found at Location : 5
1.Linear Search
2.Binary Search
3.Exit
Enter your choice:
2
<-----BINARY SEARCH----->
Enter Item you want to Search:
3
Data is Found at Location : 3
1.Linear Search
2.Binary Search
3.Exit
Enter your choice: 3

RESULT:
Thus a C program to search the elements using linear search and binary search was
implemented and executed successfully.
EX. NO: 13(B) SORTING
DATE:
AIM:
To write a C program to sort the elements using insertion sort, quick sort, bubble sort,
radix sort and selection sort.

ALGORITHM:
Step 1 : Start the program
Step 2 : Get the n elements to be sorted.
Step 3 : Sort the n elements using insertion(), by comparing the ith element from (i-1)th to 0th
element and placed in proper position according to ascending value. Repeat the above
step until the last element.
Step 4 : Sort the elements using q_sort( ) by picking an element, called a pivot, from the list.
Reorder the list so that all elements which are less than the pivot come before the pivot
and so that all elements greater than the pivot come after it. After this partitioning, the
pivot is in its final position. This is called the partition operation. Recursively sort the
sub-list of lesser elements and the sub-list of greater elements
Step 5 : Sort the elements using bubble( ) by comparing the first two elements of the array and
swap if necessary. Then, again second and third elements are compared and swapped if
it is necessary and continue this process until last and second last element is compared
and swapped. Repeat the above two steps n-1 times and print the result.
Step 6 : Sort the elements using radix_sort( ) by finding the number of passes. Take the least
significant digit of each key. Group the keys based on that digit, but otherwise keep the
original order of keys. Repeat the grouping process with each more significant digit.
Step 6 : Sort the elements using selectionsort( ), where the algorithm sorts an array by repeatedly
finding the minimum element (considering ascending order) from unsorted part and
putting it at the beginning. In every iteration of selection sort, the minimum element
(considering ascending order) from the unsorted subarray is picked and moved to the
sorted subarray.
Step 7 : Stop the program

PROGRAM:
/*Sorting*/
#include<conio.h>
#include<stdio.h>
#define MAX 100
#define SHOWPASS
//void quickSort(int numbers[], int array_size);
void q_sort(int numbers[], int left, int right);
void bubble(int *array,int length);
void insertion(int a[], int n);
void radix_sort(int *a, int n);
int findmax(int a[], int n);
void print(int *a, int n) {
int i;
for (i = 0; i < n; i++)
printf("%d\t", a[i]);
}
void selectionsort(int a[10],int k)
{
/* Selection sorting begins */
//void exchang(int b[10],int k) {
int temp, big, j, N;
for ( j=k-1; j>=1; j--)
{
big = findmax(a,j);
temp = a[big];
a[big] = a[j];
a[j] = temp;
}

printf("Sorted array is...\n");


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

/* End of main*/
/* function to find the maximum value */
int findmax(int a[10], int k)
{
int max=0,j;
for (j = 1; j <= k; j++)
{
if ( a[j] > a[max])
{
max = j;
}
}
return(max);
}

void radix_sort(int *a, int n) {


int i, b[MAX], m = 0, exp = 1;
for (i = 0; i < n; i++) {
if (a[i] > m)
m = a[i];
}
while (m / exp > 0) {
int box[10] = {
0
};
for (i = 0; i < n; i++)
box[a[i] / exp % 10]++;
for (i = 1; i < 10; i++)
box[i] += box[i - 1];
for (i = n - 1; i >= 0; i--)
b[--box[a[i] / exp % 10]] = a[i];
for (i = 0; i < n; i++)
a[i] = b[i];
exp *= 10;
#ifdef SHOWPASS
printf("\n\nPASS : ");
print(a, n);
#endif
}
}
void insertion(int a[], int n)
{
int i,j,temp;
for(i=1;i<n;i++)
{
temp=a[i];

j=i-1;
while((temp<a[j])&&(j>=0))
{
a[j+1]=a[j];
j=j-1;
}
a[j+1]=temp;
}
}
void display(int a[],int n)
{
int i;
printf("\n\t\t\tSorted List\n");
for(i=0;i<n;++i)
printf("\t%d",a[i]);
}
void q_sort(int a[], int left, int right)
{
int pivot, l_hold, r_hold;
l_hold = left;
r_hold = right;
pivot = a[left];
while (left < right)
{

while ((a[right] >= pivot) && (left < right))


right--;
if (left != right)
{
a[left] = a[right];
left++;
}
while ((a[left] <= pivot) && (left < right))
left++;

if (left != right)
{
a[right] = a[left];
right--;
}
}
a[left] = pivot;
pivot = left;
left = l_hold;
right = r_hold;
if (left < pivot)
q_sort(a, left, pivot-1);
if (right > pivot)
q_sort(a, pivot+1, right);

}
void bubble(int *array,int length)
{
int i,j;
for(i=0;i<length;i++)
{
for(j=0;j<i;j++)
{
if(array[i]>array[j])
{
int temp=array[i];
array[i]=array[j];
array[j]=temp;
}}}
}
void main()
{
int a[100],n,i,ch;
clrscr( );
printf("\nEnter The Number Of Elements\t: ");
scanf("%d",&n);
printf("\nEnter Elements\n");
for(i=0;i< n;++i)
scanf("%d",&a[i]);
while(1)
{
printf(“\n********************************\n”);
printf("\n1.Insertion sort\n2.Quick sort\n3.Bubble sort\n4.Radix sort \n5.Selection sort
6.Exit\n");
printf(“\n********************************\n”);
printf("Enter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("<-----Insertion SORT----->\n");
insertion(a,n);
display(a,n);
break;
case 2:
printf("<-----Quick SORT----->\n");
q_sort(a,0,n-1);
display(a,n);
break;
case 3:
bubble(a,n);
printf("<-----Bubble SORT----->\n");
printf("\n\t\t\tSorted List\n");
for (i=n-1;i>=0;i--)
printf("\t%d",a[i]);
break;
case 4:
radix_sort(a,n);
printf("\n\n<-----Radix SORT----->\n");
display(a,n);
break;
case 5:
selectionsort(a,n);
printf("\n\n<-----Selection SORT----->\n");
display(a,n);
break;
case 6:
exit(0);
default:
printf("Enter a Valid Choice!");
}
}
}
OUTPUT:
Enter Elements
2
4
1
3
5
********************************
1.Insertion sort
2.Quick sort
3.Bubble sort
4.Radix sort
5.Selection sort
6.Exit
********************************
Enter your choice:
1
<-----Insertion SORT----->
Sorted List

1 2 3 4 5
********************************
1.Insertion sort
2.Quick sort
3.Bubble sort
4.Radix sort
5.Selection sort
6.Exit
********************************
Enter your choice:
2
<-----Quick SORT----->
Sorted List

1 2 3 4 5
********************************
1.Insertion sort
2.Quick sort
3.Bubble sort
4.Radix sort
5.Selection sort
6.Exit
********************************
Enter your choice:
3
<-----Bubble SORT----->
Sorted List
1 2 3 4 5
********************************
1.Insertion sort
2.Quick sort
3.Bubble sort
4.Radix sort
5.Selection sort
6.Exit
********************************
Enter your choice:
4
<-----Radix SORT----->
Sorted List

1 2 3 4 5
********************************
1.Insertion sort
2.Quick sort
3.Bubble sort
4.Radix sort
5.Selection sort
6.Exit
********************************
Enter your choice:
5
<-----Selection SORT----->
Sorted List
1 2 3 4 5
********************************
1.Insertion sort
2.Quick sort
3.Bubble sort
4.Radix sort
5.Selection sort
6.Exit
********************************
Enter your choice:
6

RESULT:
Thus a C program to sort the elements using insertion sort, quick sort, bubble sort,
radix sort and selection sort was implemented and executed successfully.
EX. NO: 14(A) HASHING - SEPARATE CHAINING
DATE:
AIM:
To write a C program for the implementation of hashing using Separate Chaining.

ALGORITHM:
Step 1 : Start the program
Step 2 : Define the size of the table as 10.
Step 3 : Declare structures to store the data and the next pointer.
Step 4 : Insert the values into the hash table using insert( ), by finding the position in the table.
Step 5 : Display the final hash table using display( )
Step 6 : Stop the program

PROGRAM:
#include <stdio.h>
#include <stdlib.h>
#define TABLE_SIZE 10
struct node
{
int data;
struct node *next;
};
struct node *head[TABLE_SIZE]={NULL},*c,*p;
void insert(int i,int val)
{
struct node * newnode=(struct node *)malloc(sizeof(struct node));
newnode->data=val;
newnode->next = NULL;
if(head[i] == NULL)
head[i] = newnode;
else
{
c=head[i];
while(c->next != NULL)
c=c->next;
c->next=newnode;
}
}

void display(int i)
{
if(head[i] == NULL)
{
printf("No Hash Entry");
return;
}
else
{
for(c=head[i];c!=NULL;c=c->next)
printf("%d->",c->data);
}
}
main()
{
int opt,val,i;
while(1)
{
printf("\n1. Insert\n2. Display \n3. Exit \n");
printf("\nEnter your choice:");
scanf("%d",&opt);
switch(opt)
{
case 1:
printf("\nEnter a value to insert into hash table:\n");
scanf("%d",&val);
i=val%TABLE_SIZE;
insert(i,val);
break;
case 2: for(i=0;i<TABLE_SIZE;i++)
{
printf("\nEntries at index %d\n",i);
display(i);
}
break;
case 3: exit(0);
}
}
}
OUTPUT:
1. Insert
2. Display
3. Exit

Enter your choice:1

Enter a value to insert into hash table:


21

1. Insert
2. Display
3. Exit

Enter your choice:1

Enter a value to insert into hash table:


22

1. Insert
2. Display
3. Exit

Enter your choice:1


Enter a value to insert into hash table:
32

1. Insert
2. Display
3. Exit

Enter your choice:1

Enter a value to insert into hash table:


34

1. Insert
2. Display
3. Exit

Enter your choice:1

Enter a value to insert into hash table:


56

1. Insert
2. Display
3. Exit
Enter your choice:1

Enter a value to insert into hash table:


78

1. Insert
2. Display
3. Exit
Enter your choice:2

Entries at index 0
No Hash Entry
Entries at index 1
21->
Entries at index 2
22->32->
Entries at index 3
No Hash Entry
Entries at index 4
34->
Entries at index 5
No Hash Entry
Entries at index 6
56->
Entries at index 7
No Hash Entry
Entries at index 8
78->
Entries at index 9
No Hash Entry
1. Insert
2. Display
3. Exit
Enter your choice: 3

RESULT:
Thus a C program for hashing using Separate Chaining was implemented and
executed successfully.
EX. NO: 14(A) HASHING - LINEAR PROBING
DATE:
AIM:
To write a C program for the implementation of hashing using Linear Probing.

ALGORITHM:
Step 1 : Start the program
Step 2 : Define the size of the table as 5.
Step 3 : Declare structures to store the data and the next pointer.
Step 4 : Insert the values into the hash table using insert( ), by finding the position in the table.
Step 5 : Display the final hash table using display( )
Step 6 : Find the particular element’s position using find( )
Step 7 : Stop the program

PROGRAM:
#include <stdio.h>
#include<stdlib.h>
#define TABLE_SIZE 5
void insert(int);
void display();
void find(int);
int htable[TABLE_SIZE]={NULL};

int main()
{
int opt,val;
while(1)
{
printf("\n*******************");
printf("\n1.Insert\n2.Display\n3.Find\n4.Exit");
printf("\n*******************");
printf("\nEnter your choice:");
scanf("%d",&opt);
switch(opt)
{
case 1:
printf("\nEnter a value to insert into hash table:");
scanf("%d",&val);
insert(val);
break;
case 2: display();
break;
case 3: printf("\nEnter a value to find in the hash table:");
scanf("%d",&val);
find(val);
break;
case 4: exit(0);
}
}
}
void find(int val)
{
int index,i,flag=0,hash;
hash=val%TABLE_SIZE;
for(i=0;i<TABLE_SIZE; i++)
{
index=(hash+i)%TABLE_SIZE;
if(htable[index]==val)
{
printf("Value is found at index:%d",index);
flag=1;
break;
}
}
if(flag==0)
printf("\nValue not found!!!\n");
}
void display()
{
int i;
printf("\nelements in the hash table are \n");
for(i=0;i< TABLE_SIZE; i++)
printf("\nat index %d \t value = %d",i,htable[i]);
}
void insert(int val)
{
int index,i,flag=0,hash;
hash=val%TABLE_SIZE;
for(i=0;i<TABLE_SIZE;i++)
{
index=(hash+i)%TABLE_SIZE;
if(htable[index] == NULL)
{
htable[index]=val;
flag=1;
break;
}
}
if(flag == 0)
printf("\nElement cannot be inserted\n");
}
OUTPUT:
*******************
1.Insert
2.Display
3.Find
4.Exit
*******************
Enter your choice:1

Enter a value to insert into hash table:22

*******************
1.Insert
2.Display
3.Find
4.Exit
*******************
Enter your choice:1

Enter a value to insert into hash table:23


*******************
1.Insert
2.Display
3.Find
4.Exit
*******************
Enter your choice:1

Enter a value to insert into hash table:34

*******************
1.Insert
2.Display
3.Find
4.Exit
*******************
Enter your choice:1

Enter a value to insert into hash table:31


*******************
1.Insert
2.Display
3.Find
4.Exit
*******************
Enter your choice:2

elements in the hash table are


at index 0 value = 0
at index 1 value = 31
at index 2 value = 22
at index 3 value = 23
at index 4 value = 34
*******************
1.Insert
2.Display
3.Find
4.Exit
*******************
Enter your choice:3
Enter a value to find in the hash table:22
Value is found at index: 2
*******************
1.Insert
2.Display
3.Find
4.Exit
*******************
Enter your choice: 4

RESULT:
Thus a C program for hashing using Linear Probing was implemented and executed
successfully.
CONTENT BEYOND
THE SYLLABUS
EX. NO:15 DOUBLE ENDED QUEUE
DATE:
AIM:
To write a C program for the implementation of Deque.

ALGORITHM:
Step 1 : Start the program
Step 2 : Make the queue empty by using initialize( ).
Step 3 : Check whether the Queue is empty or not using empty( )
Step 4 : Check whether the Queue is full or not using full( )
Step 5 : Insert elements into the queue at the front and rear by using enqueueF( ) and
enqueueR( ) respectively.
Step 6 : Delete elements from the queue at the front and rear by using dequeueF( ) and
dequeueR( ) respectively.
Step 7 : Print the elements in the dequeue by using print( )
Step 8: Stop the program

PROGRAM:
#include<stdio.h>
#include<process.h>
#define MAX 30

typedef struct dequeue


{
int data[MAX];
int rear,front;
}dequeue;

void initialize(dequeue *p);


int empty(dequeue *p);
int full(dequeue *p);
void enqueueR(dequeue *p,int x);
void enqueueF(dequeue *p,int x);
int dequeueF(dequeue *p);
int dequeueR(dequeue *p);
void print(dequeue *p);
void main()
{
int i,x,op,n;
dequeue q;

initialize(&q);

do
{
printf("\n1.Create\n2.Insert(rear)\n3.Insert(front)\n4.Delete(rear)\n5.Delete(front)");
printf("\n6.Print\n7.Exit\n\nEnter your choice:");
scanf("%d",&op);

switch(op)
{
case 1: printf("\nEnter number of elements:");
scanf("%d",&n);
initialize(&q);
printf("\nEnter the data:");

for(i=0;i<n;i++)
{
scanf("%d",&x);
if(full(&q))
{
printf("\nQueue is full!!");
exit(0);
}
enqueueR(&q,x);
}
break;

case 2: printf("\nEnter element to be inserted:");


scanf("%d",&x);

if(full(&q))
{
printf("\nQueue is full!!");
exit(0);
}

enqueueR(&q,x);
break;

case 3: printf("\nEnter the element to be inserted:");


scanf("%d",&x);

if(full(&q))
{
printf("\nQueue is full!!");
exit(0);
}

enqueueF(&q,x);
break;

case 4: if(empty(&q))
{
printf("\nQueue is empty!!");
exit(0);
}

x=dequeueR(&q);
printf("\nElement deleted is %d\n",x);
break;

case 5: if(empty(&q))
{
printf("\nQueue is empty!!");
exit(0);
}

x=dequeueF(&q);
printf("\nElement deleted is %d\n",x);
break;

case 6: print(&q);
break;

default: break;
}
}while(op!=7);
}

void initialize(dequeue *P)


{
P->rear=-1;
P->front=-1;
}

int empty(dequeue *P)


{
if(P->rear==-1)
return(1);

return(0);
}

int full(dequeue *P)


{
if((P->rear+1)%MAX==P->front)
return(1);

return(0);
}

void enqueueR(dequeue *P,int x)


{
if(empty(P))
{
P->rear=0;
P->front=0;
P->data[0]=x;
}
else
{
P->rear=(P->rear+1)%MAX;
P->data[P->rear]=x;
}
}

void enqueueF(dequeue *P,int x)


{
if(empty(P))
{
P->rear=0;
P->front=0;
P->data[0]=x;
}
else
{
P->front=(P->front-1+MAX)%MAX;
P->data[P->front]=x;
}
}

int dequeueF(dequeue *P)


{
int x;

x=P->data[P->front];

if(P->rear==P->front) //delete the last element


initialize(P);
else
P->front=(P->front+1)%MAX;

return(x);
}

int dequeueR(dequeue *P)


{
int x;

x=P->data[P->rear];

if(P->rear==P->front)
initialize(P);
else
P->rear=(P->rear-1+MAX)%MAX;

return(x);
}

void print(dequeue *P)


{
if(empty(P))
{
printf("\nQueue is empty!!");
exit(0);
}

int i;
i=P->front;

while(i!=P->rear)
{
printf("\n%d",P->data[i]);
i=(i+1)%MAX;
}

printf("\n%d\n",P->data[P->rear]);
}

OUTPUT:
1.Create
2.Insert(rear)
3.Insert(front)
4.Delete(rear)
5.Delete(front)
6.Print
7.Exit
Enter your choice:1

Enter number of elements:3

Enter the data:4 6 7

1.Create
2.Insert(rear)
3.Insert(front)
4.Delete(rear)
5.Delete(front)
6.Print
7.Exit

Enter your choice:6

4
6
7

1.Create
2.Insert(rear)
3.Insert(front)
4.Delete(rear)
5.Delete(front)
6.Print
7.Exit

Enter your choice:4

Element deleted is 7

1.Create
2.Insert(rear)
3.Insert(front)
4.Delete(rear)
5.Delete(front)
6.Print
7.Exit

Enter your choice:7

RESULT:
Thus a C program for the implementation of Deque was implemen ted and executed
successfully.
EX. NO:16 PRIM’S ALGORITHM
DATE:
AIM:
To write a C program for the implementation of Minimum Spanning Tree using
Prim’s
algorithm.

ALGORITHM:
Step 1 : Start the program
Step 2 : Create edge list of given graph, with their weights.
Step 3 : Draw all nodes to create skeleton for spanning tree.
Step 4 : Select an edge with lowest weight and add it to skeleton and delete edge from edge
list.
Step 5 : Add other edges. While adding an edge take care that the one end of the edge should
always be in the skeleton tree and its cost should be minimum.
Step 6 : Repeat step 5 until n-1 edges are added.
Step 7 : Stop the program.

PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#define infinity 9999
#define MAX 20
int G[MAX][MAX],spanning[MAX][MAX],n;
int prims();
int main()
{
int i,j,total_cost;
printf("Enter 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]);
total_cost=prims();
printf("\nspanning tree matrix:\n");
for(i=0;i<n;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",spanning[i][j]);
}
printf("\n\nTotal cost of spanning tree=%d",total_cost);
return 0;
}
int prims()
{
int cost[MAX][MAX];
int u,v,min_distance,distance[MAX],from[MAX];
int visited[MAX],no_of_edges,i,min_cost,j;
//create cost[][] matrix,spanning[][]
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];
spanning[i][j]=0;
}
//initialise visited[],distance[] and from[]
distance[0]=0;
visited[0]=1;
for(i=1;i<n;i++)
{
distance[i]=cost[0][i];
from[i]=0;
visited[i]=0;
}
min_cost=0; //cost of spanning tree
no_of_edges=n-1; //no. of edges to be added
while(no_of_edges>0)
{
//find the vertex at minimum distance from the tree
min_distance=infinity;
for(i=1;i<n;i++)
if(visited[i]==0&&distance[i]<min_distance)
{
v=i;
min_distance=distance[i];
}
u=from[v];
//insert the edge in spanning tree
spanning[u][v]=distance[v];
spanning[v][u]=distance[v];
no_of_edges--;
visited[v]=1;
//updated the distance[] array
for(i=1;i<n;i++)
if(visited[i]==0&&cost[i][v]<distance[i])
{
distance[i]=cost[i][v];
from[i]=v;
}
min_cost=min_cost+cost[u][v];
}
return(min_cost);
}
OUTPUT:
Enter no. of vertices:6

Enter the adjacency matrix:


031600
305030
150564
605002
036006
004260

spanning tree matrix:


031000
300030
100004
000002
030000
004200

Total cost of spanning tree=13

RESULT:
Thus a C program for the implementation of Prim’s algorithm was implemen ted and
executed successfully.
EX. NO:17 KRUSKAL’S ALGORITHM
DATE:
AIM:
To write a C program for the implementation of Minimum Spanning Tree using
Kruskal’s algorithm.

ALGORITHM:
Step 1 : Start the program
Step 2 : Create edge list of given graph, with their weights.
Step 3 : Sort the edge list according to their weights in ascending order.
Step 4 : Draw all the nodes to create skeleton for spanning tree.
Step 5 : Pick up the edge at the top of the edge list (i.e. edge with minimum weight).
Step 6 : Remove this edge from the edge list.
Step 7 : Connect the vertices in the skeleton with given edge. If by connecting the vertices, a
cycle is created in the skeleton, then discard this edge. Repeat steps 5 to 7, until n-1
edges are added or list of edges is over.
Step 8 : Stop the program.

PROGRAM:
#include<stdio.h>

#define MAX 30

typedef struct edge


{
int u,v,w;
}edge;

typedef struct edgelist


{
edge data[MAX];
int n;
}edgelist;

edgelist elist;

int G[MAX][MAX],n;
edgelist spanlist;

void kruskal();
int find(int belongs[],int vertexno);
void union1(int belongs[],int c1,int c2);
void sort();
void print();

void main()
{
int i,j,total_cost;

printf("\nEnter number 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]);

kruskal();
print();
}

void kruskal()
{
int belongs[MAX],i,j,cno1,cno2;
elist.n=0;

for(i=1;i<n;i++)
for(j=0;j<i;j++)
{
if(G[i][j]!=0)
{
elist.data[elist.n].u=i;
elist.data[elist.n].v=j;
elist.data[elist.n].w=G[i][j];
elist.n++;
}
}

sort();
for(i=0;i<n;i++)
belongs[i]=i;

spanlist.n=0;

for(i=0;i<elist.n;i++)
{
cno1=find(belongs,elist.data[i].u);
cno2=find(belongs,elist.data[i].v);

if(cno1!=cno2)
{
spanlist.data[spanlist.n]=elist.data[i];
spanlist.n=spanlist.n+1;
union1(belongs,cno1,cno2);
}
}
}

int find(int belongs[],int vertexno)


{
return(belongs[vertexno]);
}
void union1(int belongs[],int c1,int c2)
{
int i;

for(i=0;i<n;i++)
if(belongs[i]==c2)
belongs[i]=c1;
}

void sort()
{
int i,j;
edge temp;

for(i=1;i<elist.n;i++)
for(j=0;j<elist.n-1;j++)
if(elist.data[j].w>elist.data[j+1].w)
{
temp=elist.data[j];
elist.data[j]=elist.data[j+1];
elist.data[j+1]=temp;
}
}
void print()
{
int i,cost=0;

for(i=0;i<spanlist.n;i++)
{
printf("\n%d\t%d\t%d",spanlist.data[i].u,spanlist.data[i].v,spanlist.data[i].w);
cost=cost+spanlist.data[i].w;
}

printf("\n\nCost of the spanning tree=%d",cost);


}
OUTPUT:
Enter number of vertices: 6

Enter the adjacency matrix:


031600
305030
150564
605002
036006
004260

2 0 1
5 3 2
1 0 3
4 1 3
5 2 4

Cost of the spanning tree=13

RESULT:
Thus a C program for the implementation of Kruskal’s algorithm was implemented
and executed successfully.
VIVA QUESTIONS
VIVA QUESTIONS WITH ANSWERS
1. Define Data Structures
“Data Structures ” deals with the study of how the data is organized in the memory, how efficiently
the data can be retrieved and manipulated, and the possible ways in which different data items are
logically related.

2. Define primary data structures.


Primary data structures are the basic data structures that directly operate upon the machine
instructions. All the basic constants (integers, floating-point numbers, character constants, string
constants) and pointers are considered as primary data structures.

3. Define static data structures.


A data structure formed when the number of data items are known in advance is referred as static data
structure or fixed size data structure.

4. List some of the static data structures in C


Some of the static data structures in C are arrays, pointers, structures etc.

5. Define dynamic data structures


A data structure formed when the number of data items are not known in advance is known as
dynamic data structure or variable size data structure.

6. List some of the dynamic data structures in C


Some of the dynamic data structures in C are linked lists, stacks, queues, trees etc.

7. Define linear data structures


Linear data structures are data structures having a linear relationship between its adjacent elements.
Eg) Linked lists

8. Define non-linear data structures


Non-linear data structures are data structures that don’t have a linear relationship between its adjacent
elements but have a hierarchical relationship between the elements. Eg) Trees and Graphs

9. Define Linked Lists


Linked list consists of a series of structures, which are not necessarily adjacent in memory. Each
structure contains the element and a pointer to a structure containing its successor. We call this the
Pointer. The last cell’s pointer points to NULL.

10. State the different types of linked lists


The different types of linked list include singly linked list, doubly linked list and circular linked list.

11. List the basic operations carried out in a linked list.


The basic operations carried out in a linked list include:
1.Creation of a list
2.Insertion of a node
3.Deletion of a node
4.Modification of a node
5.Traversal of the list
12. List out the advantages of linked list.
(i) It is not necessary to specify the number of elements in a linked list during its declaration
(ii) Linked list can grow and shrink in size depending upon the insertion and deletion that occurs in
the list
(iii) Insertions and deletions at any place in a list can be handled easily and efficiently
(iv) A linked list does not waste any memory space

13. List out the disadvantages of linked list.


(i)Searching a particular element in a list is difficult and time consuming.
(ii)A linked list will use more storage space than an array to store the same number of elements.

14. List out the applications of a linked list


Some of the important applications of linked lists are manipulation of polynomials, sparse matrices,
stacks and queues.

15. State the difference between arrays and linked lists

S. No Array Linked List


1. Size of an array is fixed Size of a list is variable
2. It is necessary to specify the number of It is not necessary to specify the number of
elements during declaration elements during declaration
3. Insertions and deletions are somewhat Insertions and deletions are carried out
difficult easily
4. It occupies less memory than a linked list for It occupies more memory
the same number of elements

16. Why you need a data structure?


A data structure helps you to understand the relationship of one data element with the other and
organize it within the memory. Sometimes the organization might be simple and can be very clearly
visioned. Eg) List of names of months in a year –Linear Data Structure, List of historical places in the
world- Non-Linear Data Structure. A data structure helps you to analyze the data, store it and organize
it in a logical and mathematical manner.

17.What are the four basic Operations of Data structures?


1. Traversing
2. Searching
3. Inserting
4. Deleting

18. Difference between Abstract Data Type, Data Type and Data Structure.
 An Abstract data type is the specification of the data type which specifies the logical and
mathematical model of the data type.
 A data type is the implementation of an abstract data type.
 Data structure refers to the collection of computer variables that are connected in some
specific manner.
 Data type has its root in the abstract data type and a data structure comprises a set of
computer variables of same or different data types

19. Define data type and what are the types of data type?.
Data type refers to the kinds of data that variables may hold in the programming language. Eg) int,
float, char, double – C
The following are the types of data type:
(i) Built in data type- int, float, char, double which are defined by programming language itself
(ii)User defined data type- Using the set of built in data types user can define their own data type

Eg) typedef struct student


{
int roll;
char name;
}S;
S s1 ;
Where S is a tag for user defined data type which defines the structure student and s1 is a variable of
data type S.

20. Define an Abstract Data Type (ADT).


An abstract data type is a set of operations. ADTs are mathematical abstractions; nowhere in an ADT’s
definition is there any mention of how the set of operations is implemented. Objects such as lists, sets
and graphs, along with their operations can be viewed as abstract data types.

21. Why do we need Abstract Data Types?


 Hide Unnecessary details
 Help manage software complexity
 Easier software maintenance
 Functionalities are less likely to change
 Localized the changes

22. What are the techniques for Abstract Data Types


o Data Encapsulation: It is a technique of keeping data and operations together in one
place
o Information Hiding: It is a technique of providing only sufficient details.
23. Define module.
In programming each program is breakdown into modules, so that no routine should ever exceed a
page. Each module is a logical unit and does specific job modules which in turn will call another
module.

24. What are the advantages of modularity?


1. Modules can be compiled separately which makes debugging process easier.
2. Several modules can be implemented and executed simultaneously.
3. Modules can be easily enhanced, since certain dependencies in only one routine.

25. State the difference between primitive and non-primitive data types
Primitive data types are the fundamental data types. Eg) int, float, double, charNon-primitive data
types are

26. State the difference between persistent and ephemeral data structure.
Persistent data structures are the data structures which retain their previous state and modifications
can be done by performing certain operations on it. Eg) Stack Ephemeral data structures are the data
structures which cannot retain its previous state. Eg) Queues

27. What are the objectives of studying data structures?


• To identify and create useful mathematical entities and operations to determine what classes of
problems can be solved using these entities and operations
• To determine the representation of these abstract entities and to implement the abstract operations on
these concrete representation

28. List out the different ways to implement the list?


1. Array Based Implementation
2. Linked list Implementation
i. Singly linked list
ii. Doubly linked list
iii. Cursor based linked list

29. Difference between doubly linked list and singly linked list.
S.No Singly Linked List Doubly Linked List
1. It is a collection of nodes and each node is It is a collection of nodes and each node is having
having one data field and one next field. one data field, one previous field and one next field.
2. The element can be accessed using next link. The element can be accessed using both previous
and next link.
3. No extra field is required. Hence node takes One extra field is required to store previous link
less memory space. hence node takes more memory space.
4. Less efficient access to elements More efficient access to elements.

30. List out the advantages and disadvantages of singly linked list.
Advantages:
1. Easy insertion and deletion.
2. Less time consumption.
Disadvantages:
1. Data not present in a linear manner.
2. Insertion and deletion from the front of the list is difficult without the use of header node.

31. Write the difference between doubly and circularly linked list.
S.No Doubly Linked List Circular Linked List
1. If the pointer to next node is Null, it specifies There is no first and last node.
the last node.
2. Last node’s next field is always Null Last nodes next field points to the address of the
first node.
3. Every node has three fields one is Pointer to It can be a singly linked list and doubly linked
the pervious node, next Is data and the third is list.
pointer to the next node.

32. Write the difference between cursor and pointer implementation of singly linked list.
S.No Pointer implementation Cursor implementation
1. Data are stored in a collection of structures. Data are stored in a global array of
Each structure contains a data and next pointer structures. Here array index is considered as
an address.
2. Each node is created by calling the malloc It maintains a list of free lists i.e unused
function and deleted by calling the free locations.
function. Malloc => Remove the 1st element from
free list
Free => Place the cell or element in front of
the free list.
Cursor space has slot 0 which is considered
as a header and Next is equivalent to the
pointer which points to the next slot.

cell 0 => header for free list.

33. List the applications of List ADT.


 Linked Lists can be used to implement Stacks , Queues.
 Linked Lists can also be used to implement Graphs. (Adjacency list representation of
Graph).
 Implementing Hash Tables :- Each Bucket of the hash table can itself be a linked list.
(Open chain hashing).
o Polynomial ADT : A polynomial can be represented in an array or in a
linked list by simply storing the coefficient and exponent of each term.
o Radix Sort
o Multilist

34. Define cursor implementation of list.


It is nothing but the linked list representation using array.

35. Why cursor implementation is used?


The two important items present in a pointer implementation of linked lists are
1. The data is stored in a collection of structures. Each structure contains the data and a pointer to the
next structure.
2. A new structure can be obtained from the system's global memory by a call to malloc and released
by a call to free.
Our cursor implementation must be able to simulate this. The logical way to satisfy condition 1 is to
have a global array of structure.

36.What is the principle of radix sort?


The principle of Radix Sort is to do digit by digit sort starting from least significant digit to most
significant digit. Radix sort uses counting sort as a subroutine to sort.

37. What is a Stack ?


A Stack is an ordered collection of items into which new items may be inserted and from which items
may be deleted at one end, called the top of the stack. The other name of stack is Last-in -First-out
list.

38. What are the operations of the stack?


a. CreateStack/ InitStack(Stack) – creates an empty stack
b. Push(Item) – pushes an item on the top of the stack
c. Pop(Item) – removes the top most element from the stack
d. Top(Stack) – returns the first element from the stack
e. IsEmpty(Stack) – returns true if the stack is empty

39. What are push and pop operations?


• Push – adding an element to the top of stack
• Pop – removing or deleting an element from the top of stack

40. How the operations performed on linked list implementation of stack?


a. Push and pop operations at the head of the list
b. New nodes should be inserted at the front of the list, so that they become the top of the stack
c. Nodes are removed from the front(top) of the stack

41. What are the applications of stack?


The following are the applications of stacks
• Evaluating arithmetic expressions
• Balancing the parenthesis
• Towers of Hanoi
• Function calls
• Tree traversal

42. What are the methods to implement stack in C?


The methods to implement stacks are :
 Array based
 Linked list based

43. How the stack is implemented by linked list?


It involves dynamically allocating memory space at run time while performing stack operations.
Since it consumes only that much amount of space is required for holding its data elements , it
prevents wastage of memory space.
struct stack {
int element;
struct stack *next;
}*top;

44. Write postfix from of the expression –A+B-C+D?


A-B+C-D+

45. What is a Queue?


A Queue is an ordered collection of items from which items may be deleted at one end called the front
of the queue and into which tems may be inserted at the other end called rear of the queue. Queue is
called as First –in-First-Out(FIFO).

46. What are the operations of a queue?


The operations of a queue are
 isEmpty()
 isFull()
 insert()
 delete()
 display()

47. What are enqueue and dequeue operations?


o Enqueue - adding an element to the queue at the rear end
o Dequeue – removing or deleting an element from the queue at the front end

48. What are the types of queue?


The following are the types of queue:
 Double ended queue
 Circular queue
 Priority queue

49.Define double ended queue.


It is a special type of queue that allows insertion and deletion of elements at both ends. It is also
termed as DEQUE.

50. What are the methods to implement queue in C?


The methods to implement queues are :
 Array based
 Linked list based
51. How the queue is implemented by linked list?
It is based on the dynamic memory management techniques which allow allocation and de-allocation
of memory space at runtime.
Insert operation
It involves the following subtasks:
o Reserving memory space of the size of a queue element in memory
o Storing the added value at the new location
o Linking the new element with existing queue
o Updating the rear pointer

Delete operation
It involves the following subtasks:
o Checking whether queue is empty
o Retrieving the front most element of the queue
o Updating the front pointer
o Returning the retrieved value

52. What are the applications of queue?


The following are the areas in which queues are applicable
a. Simulation
b. Batch processing in an operating systems
c. Multiprogramming platform systems
d. Queuing theory
e. Printer server routines
f. Scheduling algorithms like disk scheduling , CPU scheduling
g. I/O buffer requests

53. Define circular queue.


A Circular queue is a queue whose start and end locations are logically connected with each other.
That means the start location comes after the end location.

54. What is a Priority Queue?


Priority queue is a data structure in which the intrinsic ordering of the elements does determine the
results of its basic operations. Ascending and Descending priority queue are the two types of Priority
queue

55.Write postfix from of the expression –A+B-C+D?


A-B+C-D

56.How do you test for an empty queue?


To test for an empty queue, we have to check whether READ=HEAD where REAR is a pointer
pointing to the last node in a queue and HEAD is a pointer that pointer to the dummy header. In the
case of array implementation of queue, the condition to be checked for an empty queue is
REAR<FRONT.

57.What are the postfix and prefix forms of the expression?


o A+B*(C-D)/(P-R)
o Postfix form: ABCD-*PR-/+
o Prefix form: +A/*B-CD-PR

58.Explain the usage of stack in recursive algorithm implementation?


In recursive algorithms, stack data structures is used to store the return address when a recursive call
is encountered and also to store the values of all the parameters essential to the current state of the
procedure.

59.Write down the operations that can be done with queue data structure?
Queue is a first - in -first out list. The operations that can be done with queue are insert and remove.

60.What is a circular queue?


The queue, which wraps around upon reaching the end of the array is called as circular queue.

61. Define a tree


A tree is a finite set of one or more nodes such that there is a specially designated node called the
Root, and zero or more non empty sub trees T 1, T2....Tk, each of whose roots are connected by a
directed edge from Root R.

62. Define root


A node which doesn't have a parent. This is the unique node in the tree to which further sub-trees are
attached.

Here, A is the root.

63. Define degree of the node


The total number of sub-trees attached to that node is called the degree of the node.

For node A, the degree is 2 and for B and C, the degree is 0.

64. Define leaves


These are the terminal nodes of the tree. The nodes with degree 0 are always the leaves.
Here, B and C are leaf nodes.

65. Define internal nodes


The nodes other than the root and the leaves are called internal nodes. Here, C is the internal node.

66. Define parent node


The node which is having further sub-branches is called the parent node of those sub-
ranches.

67. Define depth and height of a node


For any node ni, the depth of ni is the length of the unique path from the root to ni. The height
of ni is the length of the longest path from ni to a leaf.

68. Define depth and height of a tree


The depth of the tree is the depth of the deepest leaf. The height of the tree is equal to the
height of the root. Always depth of the tree is equal to height of the tree.
69. What do you mean by level of the tree?
The root node is always considered at level zero, then its adjacent children are supposed to be
at level 1 and so on. Here, node A is at level 0, nodes B and C are at level 1 and nodes D and E are at
level 2.

70. Define forest


A tree may be defined as a forest in which only a single node (root) has no predecessors. Any
forest consists of a collection of trees.

71. Define a binary tree


A binary tree is a finite set of nodes which is either empty or consists of a root and two
disjoint binary trees called the left sub-tree and right sub-tree.

72. Define a path in a tree


A path in a tree is a sequence of distinct nodes in which successive nodes are connected by
edges in the tree.

73. Define a full binary tree


A full binary tree is a tree in which all the leaves are on the same level and every non-leaf
node has exactly two children.

74. Define a complete binary tree.


A complete binary tree is a tree in which every non-leaf node has exactly two children not
necessarily to be on the same level.

75. State the properties of a binary tree


• The maximum number of nodes on level n of a binary tree is 2n-1, where n≥1.
• The maximum number of nodes in a binary tree of height n is 2n-1, where n≥1.
• For any non-empty tree, nl=nd+1 where nl is the number of leaf nodes and nd is the
number of nodes of degree 2.

76. What is meant by binary tree traversal?


Traversing a binary tree means moving through all the nodes in the binary tree, visiting each
node in the tree only once.

77. What are the different binary tree traversal techniques?


• Preorder traversal
• Inorder traversal
• Postorder traversal
• Level order traversal

78. What are the tasks performed during inorder traversal?


• Traverse the left sub-tree
• Process the root node
• Traverse the right sub-tree

79. What are the tasks performed during postorder traversal?


• Traverse the left sub-tree
• Traverse the right sub-tree
• Process the root node

80. State the merits of linear representation of binary trees.


o Storage method is easy and can be easily implemented in arrays
o When the location of a parent/child node is known, other one can be determined easily
o It requires static memory allocation so it is easily implemented in all programming language

81. State the demerit of linear representation of binary trees.


Insertions and deletions in a node take an excessive amount of processing time due to data
movement up and down the array.

82. State the merit of linked representation of binary trees.


Insertions and deletions in a node involve no data movement except the rearrangement of
pointers, hence less processing time.

83. State the demerits of linked representation of binary trees.


o Given a node structure, it is difficult to determine its parent node
o Memory spaces are wasted for storing null pointers for the nodes, which have one or no sub-
trees
o It requires dynamic memory allocation, which is not possible in some programming language

84. Define a binary search tree


A binary search tree is a special binary tree, which is either empty or it should satisfy the
following characteristics:
o Every node has a value and no two nodes should have the same value i.e) the values in the
binary search tree are distinct
o The values in any left sub-tree is less than the value of its parent node
o The values in any right sub-tree is greater than the value of its parent node
o The left and right sub-trees of each node are again binary search trees
85. What is the use of threaded binary tree?
In threaded binary tree, the NULL pointers are replaced by some addresses. The left pointer of
the node points to its predecessor and the right pointer of the node points to its successor.

86. Traverse the given tree using Inorder, Preorder and Postorder traversals.

Inorder : D H B E A F C I G J
Preorder: A B D H E C F G I J
Postorder: H D E B F I J G C A

87. In the given binary tree, using array you can store the node 4 at which location?

At location 6
1 2 3 - - 4 - - 5

where LCn means Left Child of node n and RCn means Right Child of node n

88. Define AVL Tree.


An empty tree is height balanced. If T is a non-empty binary tree with T L and TR as its left and
right subtrees, then T is height balanced if
i) TL and TR are height balanced and
ii) │hL - hR│≤ 1
Where hL and hR are the heights of TL and TR respectively.

89. What do you mean by balanced trees?


Balanced trees have the structure of binary trees and obey binary search tree properties. Apart
from these properties, they have some special constraints, which differ from one data structure to
another. However, these constraints are aimed only at reducing the height of the tree, because this
factor determines the time complexity.
Eg: AVL trees, Splay trees.

90. What are the categories of AVL rotations?


Let A be the nearest ancestor of the newly inserted nod which has the balancing factor ±2. Then
the rotations can be classified into the following four categories:
Left-Left: The newly inserted node is in the left subtree of the left child of A.
Right-Right: The newly inserted node is in the right subtree of the right child of
Left-Right: The newly inserted node is in the right subtree of the left child of A.
Right-Left: The newly inserted node is in the left subtree of the right child of A.

91. What do you mean by balance factor of a node in AVL tree?


The height of left subtree minus height of right subtree is called balance factor of a node in
AVL tree.The balance factor may be either 0 or +1 or -1.The height of an empty tree is -1.

92. What is the minimum number of nodes in an AVL tree of height h?


The minimum number of nodes S(h), in an AVL tree of height h is given by S(h)=S(h-
1)+S(h-2)+1. For h=0, S(h)=1.

93. Define B-tree of order M.


A B-tree of order M is a tree that is not binary with the following structural properties:
• The root is either a leaf or has between 2 and M children.
• All non-leaf nodes (except the root) have between ┌M/2┐ and M children.
• All leaves are at the same depth.

94. What are the applications of B-tree?


• Database implementation
• Indexing on non primary key fields

95. What is the drawback of B-Trees?


The drawback of B-tree used for indexing, however is that it stores the data pointer (a pointer to the
disk file block containing the key value), corresponding to a particular key value, along with that key
value in the node of a B-tree. This technique, greatly reduces the number of entries that can be packed
into a node of a B-tree, thereby contributing to the increase in the number of levels in the B-tree,
hence increasing the search time of a record.

96. Why B+ Trees were used?


B+ tree eliminates the drawback of B-Trees by storing data pointers only at the leaf nodes of the tree.
Thus, the structure of leaf nodes of a B+ tree is quite different from the structure of internal nodes of
the B+ tree. It may be noted here that, since data pointers are present only at the leaf nodes, the leaf
nodes must necessarily store all the key values along with their corresponding data pointers to the disk
file block, in order to access them. Moreover, the leaf nodes are linked to provide ordered access to
the records. The leaf nodes, therefore form the first level of index, with the internal nodes forming the
other levels of a multilevel index. Some of the key values of the leaf nodes also appear in the internal
nodes, to simply act as a medium to control the searching of a record.

97. How to represent the structure of the internal nodes of a B+ Tree of order ‘a’?
The structure of the internal nodes of a B+ tree of order ‘a’ is as follows:
(a) Each internal node is of the form :
<P1, K1, P2, K2, ….., Pc-1, Kc-1, Pc>
where c<= a and each Pi is a tree pointer (i.e points to another node of the tree) and, each Ki
is a key value (see diagram-I for reference).
(b) Every internal node has : K1 < K2 < …. < Kc-1
(c) For each search field values ‘X’ in the sub-tree pointed at by Pi, the following condition holds :
Ki-1 < X <= Ki, for 1 < i < c and,
Ki-1 < X, for i = c
(d) Each internal nodes has at most ‘a’ tree pointers.
(e) The root node has, at least two tree pointers, while the other internal nodes have at least ceil(a/2)
tree pointers each.
(f) If any internal node has ‘c’ pointers, c <= a, then it has 'c – 1' key values.
98. How the structure of leaf nodes of B+ Tree of order ‘b’ represented?
The structure of the leaf nodes of a B+ tree of order ‘b’ is as follows:
(a) Each leaf node is of the form :
<<K1,D1>, <K2,D2>, ….., <Kc-1,Dc-1>,Pnext>
where c <= b and each Di is a data pointer (i.e points to actual record in the disk whose key value
is Ki or to a disk file block containing that record) and, each Ki is a key valueand, Pnext points to
next leaf node in the B+ tree.
(b) Every leaf node has : K1 < K2 < …. < Kc-1, c <= b
(c) Each leaf node has at least \ceil(b/2) values.
(d) All leaf nodes are at same level.

Using the Pnext pointer it is viable to traverse all the leaf nodes, just like a linked list, thereby achieving
ordered access to the records stored in the disk.

99. Define Binary heap.


o A Binary Heap is a Binary Tree with following properties.
1) It’s a complete tree (All levels are completely filled except possibly the last level and the
last level has all keys as left as possible). This property of Binary Heap makes them suitable
to be stored in an array.
o A Binary Heap is either Min Heap or Max Heap. In a Min Binary Heap, the key at root must
be minimum among all keys present in Binary Heap. The same property must be recursively
true for all nodes in Binary Tree. Max Binary Heap is similar to MinHeap.

100. How is Binary Heap represented?


A Binary Heap is a Complete Binary Tree. A binary heap is typically represented as an array.
 The root element will be at Arr[0].
 Below table shows indexes of other nodes for the i th node, i.e., Arr[i]:
Arr[(i-1)/2] Returns the parent node
Arr[(2*i)+1] Returns the left child node
Arr[(2*i)+2] Returns the right child node

101. Which method is used to achieve array representation in Heap?


The traversal method use to achieve Array representation is Level Order

102. What are the operations on MinHeap?


1) getMini(): It returns the root element of Min Heap. Time Complexity of this operation is O(1).
2) extractMin(): Removes the minimum element from MinHeap. Time Complexity of this Operation
is O(Logn) as this operation needs to maintain the heap property (by calling heapify()) after removing
root.
3) decreaseKey(): Decreases value of key. The time complexity of this operation is O(Logn). If the
decreases key value of a node is greater than the parent of the node, then we don’t need to do
anything. Otherwise, we need to traverse up to fix the violated heap property.
4) insert(): Inserting a new key takes O(Logn) time. We add a new key at the end of the tree. IF new
key is greater than its parent, then we don’t need to do anything. Otherwise, we need to traverse up to
fix the violated heap property.
5) delete(): Deleting a key also takes O(Logn) time. We replace the key to be deleted with minum
infinite by calling decreaseKey(). After decreaseKey(), the minus infinite value must reach root, so we
call extractMin() to remove the key.

103. What are the applications of Heap?


1) Heap Sort: Heap Sort uses Binary Heap to sort an array in O(nLogn) time.
2) Priority Queue: Priority queues can be efficiently implemented using Binary Heap because it
supports insert(), delete() and extractmax(), decreaseKey() operations in O(logn) time. Binomoial
Heap and Fibonacci Heap are variations of Binary Heap. These variations perform union also
efficiently.
3) Graph Algorithms: The priority queues are especially used in Graph Algorithms like Dijkstra’s
Shortest Path and Prim’s Minimum Spanning Tree.
4) Many problems can be efficiently solved using Heaps. See following for example.
a) K’th Largest Element in an array.
b) Sort an almost sorted array/
c) Merge K Sorted Arrays.

104. Define Graph.


A graph G consist of a nonempty set V which is a set of nodes of the graph, a set E which is the
set of edges of the graph, and a mapping from the set for edge E to a set of pairs of elements of V. It
can also be represented as G=(V, E).

105. Define adjacent nodes.


Any two nodes which are connected by an edge in a graph are called adjacent nodes. For
example, if an edge x ε E is associated with a pair of nodes (u,v) where u, v ε V, then we say that the
edge x connects the nodes u and v.

106. What is a directed graph?


A graph in which every edge is directed is called a directed graph.

107. What is an undirected graph?


A graph in which every edge is undirected is called a directed graph.

108. What is a loop?


An edge of a graph which connects to itself is called a loop or sling.

109. What is a simple graph?


A simple graph is a graph, which has not more than one edge between a pair of nodes than
such a graph is called a simple graph.

110. What is a weighted graph?


A graph in which weights are assigned to every edge is called a weighted graph.

111. Define out degree of a graph?


In a directed graph, for any node v, the number of edges which have v as their initial node is
called the out degree of the node v.

112. Define in degree of a graph?


In a directed graph, for any node v, the number of edges which have v as their terminal node
is called the in degree of the node v.

113. Define path in a graph?


The path in a graph is the route taken to reach terminal node from a starting node.

114. What is a simple path?


A path in a diagram in which the edges are distinct is called a simple path. It is also called as
edge simple.

115. What is a cycle or a circuit?


A path which originates and ends in the same node is called a cycle or circuit.

116. What is an acyclic graph?


A simple diagram which does not have any cycles is called an acyclic graph.

117. What is meant by strongly connected in a graph?


An undirected graph is connected, if there is a path from every vertex to every other vertex. A
directed graph with this property is called strongly connected.

118. When is a graph said to be weakly connected?


When a directed graph is not strongly connected but the underlying graph is connected, then
the graph is said to be weakly connected.

119. Name the different ways of representing a graph?


a. Adjacency matrix
b. Adjacency list

120.What is an undirected acyclic graph?


When every edge in an acyclic graph is undirected, it is called an undirected acyclic graph. It
is also called as undirected forest.
121. What are the two traversal strategies used in traversing a graph?
a. Breadth first search
b. Depth first search

122. List the two important key points of depth first search.
i) If path exists from one node to another node, walk across the edge – exploring the edge.
ii) If path does not exist from one specific node to any other node, return to the previous node
where we have been before – backtracking.

123. What do you mean by breadth first search (BFS)?


BFS performs simultaneous explorations starting from a common point and spreading out
independently.

124. Differentiate BFS and DFS.


No. DFS BFS
1. Backtracking is possible from a Backtracking is not possible
dead end
2. Vertices from which exploration is The vertices to be explored are organized as a
incomplete are processed in a FIFO queue
LIFO order
3. Search is done in one particular The vertices in the same level are maintained
Direction parallely

125. What do you mean by shortest path?


A path having minimum weight between two vertices is known as shortest path, in which
weight is always a positive number.

126. Define Activity node graph.


Activity node graphs represent a set of activities and scheduling constraints. Each node
represents an activity (task), and an edge represents the next activity.

127. Define adjacency list.


Adjacency list is an array indexed by vertex number containing linked lists. Each node Vi the
ith array entry contains a list with information on all edges of G that leave V i. It is used to represent
the graph related problems.

128. Define Connected graph.


An undirected graph is connected if there is a path from every vertex to every other vertex. A
directed graph with this property is called as strongly connected connected graph. If a directed graph
is not strongly connected but the underline graph Without direction is connected it is called as a
weakly connected graph.

129. What are the conditions for a graph to become a tree?


A graph is a tree if it has two properties.
i) If it is a connected graph.
ii) There should not be any cycles in the graph.

130. Define adjacency matrix


Adjacency matrix consists of a n*n matrix where n is the no. of vertices present. In the graph,which
consists of values either 0 or 1.
131. Define adjacency linked list.
It consists of a table with the no. of entries for each vertex for each entry a linked list is inititated for
the vertices adjacent to the corresponding table entry.

132. Define biconnectivity.


A biconnected graph is a connected and "nonseparable" graph, meaning that if any one vertex were
to be removed, the graph will remain connected. Therefore a biconnected graph has no articulation
vertices.

133.Define Topological sort.


A topological sort or topological ordering of a directed graph is a linear ordering of its vertices
such that for every directed edge uv from vertex u to vertex v, u comes before v in the ordering.

Topological Sort : 5 4 2 3 1 0

134. Define cut vertex.


A vertex in an undirected connected graph is an articulation point (or cut vertex) iff removing it (and
edges through it) disconnects the graph. It can be thought of as a single point of failure. Any graph
that contains an articulation point is inherently fragile because deleting that single vertex causes a loss
of connectivity between other nodes. If a graph does not have an articulation point, then it is said to be
biconnected.

135. Define Euler’s circuit.


An Euler circuit is a circuit that uses every edge of a graph exactly once. An Euler circuit starts and
ends at the same vertex.
136. Define Searching.
Search is a process of finding a value in a list of values. In other words, searching is the process of
finding the location of a given element in the array.
137. What are the types of searching?

138. Define Linear Search.


Linear search algorithm finds given element by comparing search element with the first element in the
list. If both are matching then results with element found, otherwise, repeat the same with the next
element in the list until search element is compared with last element in the list, if that last element
also doesn't match, then the result is "Element not found in the list".

139. Define Binary Search.


Binary search process starts comparing of the search element with the middle element in the list. If
both are matched, then the result is "element found". Otherwise, we check whether the search element
is smaller or larger than the middle element in the list. If the search element is smaller, then we repeat
the same process for left sub list of the middle element. If the search element is larger, then we repeat
the same process for right sub list of the middle element. We repeat this process until we find the
search element in the list or until we left with a sublist of only one element.

140. What are the advantages and drawbacks of Binary Search?


Advantages:
 Used with only sorted list of element. That means, binary search can be used only with list of
element which are already arranged in an order.

Drawbacks:
 Cannot be used for list of element which is in random order.

141. What is meant by sorting?


Sorting refers to arranging data in a particular format. Sorting algorithm specifies the way to arrange
data in a particular order. Most common orders are in numerical or lexicographical order.

142. What are the two main classifications of sorting based on the source of data?
a. Internal sorting
b. External sorting
What are the two main classifications of sorting based on the space?
o In-place sorting
o Not in-place sorting

143. What are in-place and not in-place sorting with examples?
Sorting algorithms may require some extra space for comparison and temporary storage of few data
elements. These algorithms do not require any extra space and sorting is said to happen in-place, or
for example, within the array itself. This is called in-place sorting. Bubble sort is an example of in-
place sorting.
However, in some sorting algorithms, the program requires space which is more than or equal to the
elements being sorted. Sorting which uses equal or more space is called not-in-place sorting. Merge-
sort is an example of not-in-place sorting.

144. What are the two main classifications of sorting based on the sequence of content?
o Stable sorting
o Unstable sorting

145. Define stable and unstable sorting.


If a sorting algorithm, after sorting the contents, does not change the sequence of similar content in
which they appear, it is called stable sorting.
If a sorting algorithm, after sorting the contents, changes the sequence of similar content in which
they appear, it is called unstable sorting.

146. Define bubble sort.


Bubble sort is a simple sorting algorithm. This sorting algorithm is comparison-based algorithm in
which each pair of adjacent elements is compared and the elements are swapped if they are not in
order.

147. What are the advantages and disadvantages of bubble sort?


Advantages
 It is popular and easy to implement.
 Elements are swapped in place without using additional temporary storage, so the space
requirement is at a minimum.
Disadvantage
 It does not deal well with a list containing a huge number of items. This is because the bubble
sort requires n-squared processing steps for every n number of elements to be sorted.

148. Define Selection sort.


Selection sort is a simple sorting algorithm. This sorting algorithm is an in-place comparison-based
algorithm in which the list is divided into two parts, the sorted part at the left end and the unsorted
part at the right end. Initially, the sorted part is empty and the unsorted part is the entire list. The
smallest element is selected from the unsorted array and swapped with the leftmost element, and that
element becomes a part of the sorted array. This process continues moving unsorted array boundary
by one element to the right.

149. What are the advantages and disadvantages of Selection sort?


Advantages:
 It performs well on a small list.
 Since it is an in-place sorting algorithm, no additional temporary storage is required beyond
what is needed to hold the original list.
Disadvantages:
 Poor efficiency when dealing with a huge list of items.
 Requires n-squared number of steps for sorting n elements.
 Its performance is easily influenced by the initial ordering of the items before the sorting
process. Because of this, the selection sort is only suitable for a list of few elements that are in
random order.

150. Define insertion sort.


An element which is to be 'insert'ed in this sorted sub-list, has to find its appropriate place and then it
has to be inserted there. Hence the name, insertion sort. The array is searched sequentially and
unsorted items are moved and inserted into the sorted sub-list (in the same array).

151. What are the advantages and disadvantages of insertion sort?


Advantages
 Simplicity.
 It also exhibits a good performance when dealing with a small list.
 The insertion sort is an in-place sorting algorithm so the space requirement is minimal.
Disadvantages
 It does not perform as well as other, better sorting algorithms.
 With n-squared steps required for every n element to be sorted, the insertion sort does not deal
well with a huge list. Therefore, the insertion sort is particularly useful only when sorting a
list of few items.

152. Define Shell sort.


Shell sort is a highly efficient sorting algorithm and is based on insertion sort algorithm. This
algorithm avoids large shifts as in case of insertion sort, if the smaller value is to the far right and has
to be moved to the far left. This algorithm uses insertion sort on a widely spread elements, first to sort
them and then sorts the less widely spaced elements. This spacing is termed as interval.

153. What are the advantages and disadvantages of Shell sort?


Advantages
 It is only efficient for medium size lists.
 For bigger lists, the algorithm is not the best choice.
 Fastest of all sorting algorithms.
 5 times faster than the bubble sort and a little over twice as fast as the insertion sort, its
closest competitor.
Disadvantages
 It is a complex algorithm and its not nearly as efficient as the merge, heap and quick sorts.
 It is still significantly slower than the merge, heap, and quick sorts, but its relatively simple
algorithm makes it a good choice for sorting lists of less than 5000 items unless speed
important.
 It's also an excellent choice for repetitive sorting of smaller lists.

154. Define Radix sort.


 Radix Sort is the generalised form of Bucket sort.
 It can be performed using buckets from 0 to 9.
 In First Pass, all the elements are sorted according to the least significant bit.
 In second pass, the numbers are arranged according to the next least significant bit and so on
this process is repeated until it reaches the most significant bits of all numbers.
 The numbers of passes in a Radix Sort depends upon the number of digits in the numbers
given.

155. What are the advantages and disadvantages of Radix sort?


Advantages:
1. Fast when the keys are short i.e. when the range of the array elements is less.
2. Used in suffix array construction algorithms like Manber's algorithm and DC3 algorithm.

Disadvantages:
1. Since Radix Sort depends on digits or letters, Radix Sort is much less flexible than other sorts.
Hence, for every different type of data it needs to be rewritten.
2. The constant for Radix sort is greater compared to other sorting algorithms.
3. It takes more space compared to Quicksort which is inplace sorting.

156. Define Hashing.


It is an effective way to store the elements in some data structures.

157. Define Hash Table.


 It is a data structure used for storing and retrieving data very quickly.
 Insertion of data in the hash table is based on the key value.
 Hence every data in the hash table is associated with some key. For eg. For storing an
employee record in the hash table the employee ID will work as a key.

158. Define Hash Function


 It is a function which is used to put the data in the hash table.
 One can use the same hash function to retrieve the data from the hash table. Thus hash
function is used to implement the hash table. The integer returned by the hash function is
called hash key.

Example: HASH (KEYVALUE) = KEYVALUE MOD TABLESIZE

159. Name some methods of Hashing Function


o Division Method
o Mid - Square Method
o Multiplicative Hash Function
o Folding Method
o Digit Analysis

160. Define Fold shift and Fold boundary.


In fold shift, the key value is divided into parts whose size matches the size of the required address.
Then the left and right parts are shifted and added with the middle part. In fold boundary, the left and
right numbers are folded on a fixed boundary between them and the center number.

Fold shift:
Key = 123456789
123 + 456 + 789 =1368 (1 is discarded)
The record will be placed at location 368 in the table.

Fold boundary:
Key = 123456789
321 + 654 + 987 = 1962(1 is discarded)
The record will be placed at location 962 in the table.

161. What do you mean by digit analysis?


This hashing function is a distribution-dependent. Here we make a statistical analysis of digits
of the key, and select those digits (of fixed position) which occur quite frequently. Then reverse or
shifts the digits to get the address.
162. What do you mean by collision?
Collision occurs when a hash value of a record being inserted hashes to an address (i.e. Relative
position) that already contain a different record. (ie) When two key values hash to the same position.

163. What is collision resolution?


The process of finding another position for the collide record.
164. Name some Collision Resolution Techniques.
1. Separate Chaining (or) External Hashing
2. Open Addressing (or) Closed Hashing

165. Define Separate Chaining.


 Separate chaining is an open hashing technique.
 Separate chaining is a collision resolution technique, in which we can keep the list of all
elements that hash to the same value. This is called separate chaining because each hash table
element is a separate chain(linked list).
 A pointer field is added to each record location.

166. What are the advantages of Separate Chaining?


 More number of elements can be inserted as it uses array of linked lists.
 The elements having the same memory address will be in the same chain and hence leads to
faster searching.
 Doesn’t require a prior knowledge on the number of elements that are to be stored in the hash
table (i.e.,) Dynamic memory allocation is done.
 It helps to get a uniform and perfect collision resolution hashing.

167. What are the disadvantages of Separate Chaining?


 It requires pointers, which occupies more memory space. This leads to slow the algorithm
down a bit of the time required to allocate the new cells, and also essentially requires the
implementation of a second data structure.
 The elements are not evenly distributed. Some hash index may have more elements and some
may not have anything.

168. Define Open addressing.


 Open addressing is also called Closed Hashing, which is an alternative to resolve the
collisions with linked lists.
 In this hashing system, if a collision occurs, alternative cells are tried until an empty cell is
found.
 A hash table may use open addressing, which means that each slot in the hash table contains
either a single key or NIL to indicate that no key has been hashed in that slot.

169. Name some common collision resolution strategies.


(i) Linear Probing
(ii) Quadratic probing
(iii) Double Hashing.

170. Define Linear Probing.


 In linear probing, the position in which a key can be stored is found by sequentially searching
all position starting from the position calculated by the hash function until an empty cell is
found.
 If the end of the table is reached and no empty cells has been found, then the search is
continued from the beginning of the table. It has a tendency to create clusters in the table.
171. What are the advantages and disadvantages of Linear Probing?
Advantages :
 It doesn't require pointers.
 It is very simpler to implement.

Disadvantages:
 It forms clusters, which degrades the performance of the hash table for storing and retrieving.
(Primary clustering: Large clusters of occupied (active or deleted) cells may form during
linear probing.)
 If any collision occurs when the hash table becomes half full, it is difficult to find an empty
location in the hash table and hence the insertion process takes a longer time.

172. What are the applications of hashing?


 Compilers use hash tables to keep track of declared variables (symbol table).
 A hash table can be used for on-line spelling checkers — if misspelling detection (rather
than correction) is important, an entire dictionary can be hashed and words checked in
constant time.
 Game playing programs use hash tables to store seen positions, thereby saving computation
time if the position is encountered again.

173. When to use Hashing?


 Hash tables are very good if there is a need for many searches in a reasonably stable table.
 Hash tables are not so good if there are many insertions and deletions, or if table
traversals are needed — in this case, AVL trees are better.
 Hashing is very slow for any operations which require the entries to be sorted
e.g. Find the minimum key

174. Define Rehashing.


 If the table is close to full, the search time grows and may become equal to the table size.
 When the load factor exceeds a certain value (e.g. greater than 0.5) we do rehashing :
o Build a second table twice as large as the original and rehash there all the keys of the
original table.

175. Define Extendible hashing.


Extendible Hashing is a dynamically updateable disk-based index structure which implements
a hashing scheme utilizing a directory. The index is used to support exact match queries, i.e. find the
record with a given key.

176. What are the benefits of extendible hashing?


It is used when the amount of data is too large to fit in main memory and external storage is used.
i.e.,N records in total to store, M records in one disk block

177. Define Overflow Handling.


If a bucket overflow happens, the bucket is split into two. The directory may or may not double,
depending on whether the local depth of the overflown bucket was equal to the global depth before
split.

178. What are the advantages of Extendible Hashing?


 Compared with the B+-tree index which also supports exact match queries (in logarithmic
number of I/Os), Extendible Hashing has better expected query cost O(1) I/O.
 Compared with Linear Hashing, Extendible Hashing does not have any overflow page.
Overflows are handled by doubling the directory which logically doubles the number of
buckets. Physically, only the overflown bucket is split.

179. What are the applications of Extendible Hashing?


Extendible Hashing can be used in applications where exact match query is the most important query
such as hash join

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy