Ds Lab Manual - 2018
Ds Lab Manual - 2018
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 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;
}
}
}while(pos>CURRENTSIZE || pos<0);
}
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");
}
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;
};
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;
}
}
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);
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
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
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();
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!!!
Insertion success!!!
Insertion success!!!
Deleted : 22
***** MENU *****
1. Insertion
2. Deletion
3. Display
4. Exit
Enter your choice: 3
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;
};
void main()
{
int choice,data;
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
}
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
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
1. Enqueue
2. Dequeue
3. Display
4. Exit
22 54 48
1. Enqueue
2. Dequeue
3. Display
4. Exit
1. Enqueue
2. Dequeue
3. Display
4. Exit
54 48
1. Enqueue
2. Dequeue
3. Display
4. Exit
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>
int main(void) {
int ch;
do {
my_poly * poly1, * poly2, * poly3;
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;
}
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
Addition is completed
The polynomial expression is:
7x^3 + 6x^2 + 11x^1 + 5x^0
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
char stack[MAX];
char pop();
void push(char item);
{
switch(symbol)
{
case '+':
case '-':
return 2;
break;
case '*':
case '/':
return 4;
break;
case '^':
case '$':
return 6;
break;
case '(':
case ')':
case '#':
return 1;
break;
}
}
default:
return 0;
}
}
{
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();
}
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);
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
1.Insert.
2.Delete.
3.Display.
4.Quit.
------------------------------------------------------------------------------
2.Delete.
3.Display.
4.Quit.
------------------------------------------------------------------------------
Input the data to be added in the queue : 24
------------------------------------------------------------------------------
--------------------------- MAIN MENU -------------------------------------
1.Insert.
2.Delete.
3.Display.
4.Quit.
Enter your choice : 3
Priority Data
1 24
2 23
2.Delete.
3.Display.
4.Quit.
1.Insert.
2.Delete.
3.Display.
4.Quit.
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;
};
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);
}
}
}
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>
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;
return 0;
}
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(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);
}
return(y);
}
return(T);
}
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);
}
OUTPUT:
********************
1)Create
2)Insert
3)Delete
4)Print
5)Exit
********************
Enter Your Choice:1
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>
int count = 0;
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);
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
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;
};
return graph;
}
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
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
for(i=1;i<=n;i++)
if(vis[i]==0)
bfs(i,n);
}
OUTPUT:
Enter the number of vertices:3
*************************
**********MENU***********
*************************
1.Breadth First Search
2.Depth First Search
Enter your choice:1
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
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]);
return 0;
}
int cost[MAX][MAX],distance[MAX],pred[MAX];
int visited[MAX],count,mindistance,nextnode,i,j;
distance[startnode]=0;
visited[startnode]=1;
count=1;
while(count<n-1)
{
mindistance=INFINITY;
j=i;
do
{
j=pred[j];
printf("<-%d",j);
}while(j!=startnode);
}
}
OUTPUT:
Enter no. of vertices:5
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;
graph->E = E;
graph->edge = (struct Edge*) malloc( graph->E * sizeof( struct Edge ) );
return graph;
}
int E = graph->E;
int StoreDistance[V];
int i,j;
StoreDistance[source] = 0;
int v = graph->edge[j].destination;
int v = graph->edge[i].destination;
FinalSolution(StoreDistance, V);
return;
}
int main()
{
int V,E,S; //V = no.of Vertices, E = no.of Edges, S is source vertex
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
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;
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;
}
/* 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);
}
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)
{
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
1. Insert
2. Display
3. Exit
1. Insert
2. Display
3. Exit
1. Insert
2. Display
3. Exit
1. Insert
2. Display
3. Exit
1. Insert
2. Display
3. Exit
Enter your choice:1
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
*******************
1.Insert
2.Display
3.Find
4.Exit
*******************
Enter your choice:1
*******************
1.Insert
2.Display
3.Find
4.Exit
*******************
Enter your choice:1
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
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;
if(full(&q))
{
printf("\nQueue is full!!");
exit(0);
}
enqueueR(&q,x);
break;
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);
}
return(0);
}
return(0);
}
x=P->data[P->front];
return(x);
}
x=P->data[P->rear];
if(P->rear==P->front)
initialize(P);
else
P->rear=(P->rear-1+MAX)%MAX;
return(x);
}
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
1.Create
2.Insert(rear)
3.Insert(front)
4.Delete(rear)
5.Delete(front)
6.Print
7.Exit
4
6
7
1.Create
2.Insert(rear)
3.Insert(front)
4.Delete(rear)
5.Delete(front)
6.Print
7.Exit
Element deleted is 7
1.Create
2.Insert(rear)
3.Insert(front)
4.Delete(rear)
5.Delete(front)
6.Print
7.Exit
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
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
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;
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);
}
}
}
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;
}
2 0 1
5 3 2
1 0 3
4 1 3
5 2 4
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.
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
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
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.
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
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.
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
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.
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.
Topological Sort : 5 4 2 3 1 0
Drawbacks:
Cannot be used for list of element which is in random 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
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.
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.
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.