Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Dsa Manual Final

Download as pdf or txt
Download as pdf or txt
You are on page 1of 65

KARPAGAM ACADEMY OF HIGHER EDUCATION

(Deemed to be University Established Under Section 3 Of UGC Act 1956)


Pollachi Main Road, Eachanari Post, Coimbatore – 641 021, INDIA
Phone : 0422-6471113-5, 6453777 Fax No : 0422 -2980022-3
Email : info@karpagam.com Web : www.kahedu.edu.in

Faculty of Engineering
Department of Computer Science and
Engineering

Data Structures and Algorithms


Laboratory manual

PREPARED BY Verified by
Mrs.G.Kalpna/Dr.Lanitha.B
CSE/KAHE

1
DATA STRUCTURES AND ALGORITHMS LABORATORY

Course Objectives:
 To understand the basic concepts of different data structures
 To choose the appropriate data structure to design a specified application.
 To Determine which algorithm or data structure to be used in different scenarios
 To analyze the performance of algorithms.
 To demonstrate understanding of the abstract properties of various data structures
such as stacks, queues, lists, trees and graphs and understanding of various sorting
algorithms, including bubble sort, selection sort, heap sort and quick sort.
 To Understand and apply fundamental algorithmic problems including Tree
traversals, Graph traversals, and shortest paths.

Laboratory Outcomes:

 Understand the importance of data structures and abstract data types, and their basic
usability in different applications through programming languages.
 Analyze and differentiate different algorithms based on their time complexity.
 Be capable to identity the appropriate data structure for given problem
 Implement both linear and non-linear data structures and their operations
 Able to understand various data structure such as stacks, queues, trees, graphs, etc. to
solve various computing problems.
 Have practical knowledge on the applications of data structures.

List of Experiments:
1. Implementation of List using Arrays
2. Implementation of Singly Linked List
3. Implementation of Linked Stack
4. Implementation of Linked Queue
5. Implementation of any two stack applications
6. Implementation of Insertion Sort
7. Implementation of Merge Sort
8. Implementation of Quick Sort
9. Implementation of Insertion operation in Binary Search Tree
10. Implementation of Tree Traversals
11. Implementation of Hashing with any one collision resolution method
12. Implementation of Dijkstra’s Shortest Path Algorithm

2
Instructions to the students

The following instructions must be followed by the students in their laboratory classes.

1) Students are expected to be punctual to the lab classes. If they are late, they will be
considered absent for that particular session.

2) Students should strictly maintain the dress code.

3) Students must bring their Workbook, record note (completed with previous experiment) to
every lab class without fail.

4) Students are advised to come with full preparation for their lab sessions by

Reading the detailed procedure of the exercise from the laboratory manual.

Completion of Workbook (i.e.) Aim, Procedure, Algorithm, Program should be written


and Flowchart should be drawn in the observation note before entering into the
laboratory.

5) Students must use pen for writing and pencil to draw Flowchart in Work book.

6) Students must get attestations immediately for their output/execution.

7) Students are advised to enter their results evaluated in the Work book on the same day of
that exercise.

8) Assessment marks for each exercise is based only on their performance in the laboratory.

9) Record note has to be completed then and there and get corrected when the students are
coming for the next lab class.

10) Students must strictly maintain silence during lab classes.

11) If any of the students is absent for the lab class for genuine reasons, he/she will be permitted
to do the exercise during the repetition class only.

12) If any student is found causing damage to the lab equipments, he/she shall replace the same
with a new.

3
Common to

20BTAD342 – DATA STRUCTURES

20BECS342- DATA STRUCTURES AND ALGORITHMS

20BEEC341 - DATA STRUCTURES AND ALGORITHMS

4
List of Experiments

1 Implementation of List using Arrays

2 Implementation of Singly Linked List

3 Implementation of Linked Stack

4 Implementation of Linked Queue

5 Implementation of any two stack applications

6 Implementation of Insertion Sort

7 Implementation of Merge Sort

8 Implementation of Quick Sort

9 Implementation of Insertion operation in Binary Search Tree

10 Implementation of Tree Traversals

11 Implementation of Hashing with any one collision resolution method

12 Implementation of Dijkstra’s Shortest Path Algorithm

5
Data Structure and Algorithms

Data Structures are the programmatic way of storing data so that data can be used efficiently.
Almost every enterprise application uses various types of data structures in one or the other way.
This tutorial will give you a great understanding on Data Structures needed to understand the
complexity of enterprise level applications and need of algorithms, and data structures.
As applications are getting complex and data rich, there are three common problems that
applications face now-a-days.
 Data Search − Consider an inventory of 1 million(106) items of a store. If the application is
to search an item, it has to search an item in 1 million(106) items every time slowing down the
search. As data grows, search will become slower.
 Processor speed − Processor speed although being very high, falls limited if the data grows
to billion records.
 Multiple requests − As thousands of users can search data simultaneously on a web server,
even the fast server fails while searching the data.
To solve the above-mentioned problems, data structures come to rescue. Data can be organized in
a data structure in such a way that all items may not be required to be searched, and the required
data can be searched almost instantly.
Algorithm is a step-by-step procedure, which defines a set of instructions to be executed in a
certain order to get the desired output. Algorithms are generally created independent of underlying
languages, i.e. an algorithm can be implemented in more than one programming language.
From the data structure point of view, following are some important categories of algorithms −
 Search − Algorithm to search an item in a data structure.
 Sort − Algorithm to sort items in a certain order.
 Insert − Algorithm to insert item in a data structure.
 Update − Algorithm to update an existing item in a data structure.
 Delete − Algorithm to delete an existing item from a data structure.

C Programming
C programming is a general-purpose, procedural, imperative computer programming
language developed in 1972 by Dennis M. Ritchie at the Bell Telephone Laboratories to develop the
UNIX operating system. C is the most widely used computer language. It keeps fluctuating at
number one scale of popularity along with Java programming language, which is also equally
popular and most widely used among modern software programmers.

o The UNIX OS was totally written in C.


6
o Today C is the most widely used and popular System Programming Language.

o Most of the state-of-the-art software have been implemented using C.

o Today's most popular Linux OS and RDBMS MySQL have been written in C.

7
Ex.No: 1
List Using Arrays
Date :
Aim:

To write a C program to implement list using array.

Description:

 Arrays are defined as the collection of similar type of data items stored at contiguous memory
locations.
 Arrays are the derived data type in C programming language which can store the primitive type
of data such as int, char, double, float, etc.
 Array is the simplest data structure where each data element can be randomly accessed by using
its index number.
Following are the important terms to understand the concept of Array.
 Element − Each item stored in an array is called an element.
 Index − Each location of an element in an array has a numerical index, which is used to identify
the element.

Algorithm:

Step 1: Start.
Step 2: Declare the necessary functions for implementation.
Step 3: Get the input from the user and store it an array.
Step 4: Get the position for Insertion, shift the elements right till the position and insert the required
element.
Step 5: Get the position to delete, and shift the elements left to delete the required element.
Step 6: For searching get the element and traverse the array until the element is found
Step7: Display function is used to output the array.
Step 8: Stop.

Code:

#include<stdio.h>
void create();
void insert();
void deletion();
void search();
void display();
int a,b[20], n, p, e, f, i, pos;

8
void main()
{
int ch;
char g='y';
do
{
printf("\n Main Menu");
printf("\n 1.Create \n 2.Delete \n 3.Search \n 4.Insert \n 5.Display\n 6.Exit \n");
printf("\n Enter your Choice :");
scanf("%d", &ch);
switch(ch)
{
case 1:
create(); break;
case 2:
deletion();break;
case 3:
search();break;
case 4:
insert();break;
case 5:
display();break;
default:
printf("\n Enter the correct choice:"); }
printf("\n Do u want to continue::(y/n)");
scanf("\n%c", &g);
}
while(g=='y'||g=='Y');
}

void create()
{
printf("\n Enter the number of nodes:");
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("\n Enter the Element:");
scanf("%d", &b[i]);
}
}

9
void deletion()
{
printf("\n Enter the position u want to delete:");
scanf("%d", &pos);
if((pos>n)||(pos<=0))
{
printf("\n Invalid Location:");
}
else
{
for(i=pos;i<n;i++)
{
b[i-1]=b[i];
}
n--;
}
printf("\n The Elements are:");
for(i=0;i<n;i++)
{
printf("\t%d", b[i]);
}
}

void search()
{
int flag=0;
printf("\n Enter the Element to be searched:");
scanf("%d", &e);
for(i=0;i<n;i++)
{
if(b[i]==e)
{
flag=1;
}
}
if (flag==1)
printf(" Value %d is in the list:", e);
else
printf(" Value is not in list:");
}

10
void insert()
{
printf("\n Enter the position u need to insert::");
scanf("%d", &pos);
if((pos>n+1)||(pos<=0))
{
printf("\n Invalid Location:");
}
else
{
for(i=n-1;i>=pos-1;i--)
{
b[i+1]=b[i];
}
printf("\n Enter the element to insert:\n");
scanf("%d",&p);
b[pos-1]=p;
n++;
}
display();
}

void display()
{
printf("\n The Elements of The list ADT are:");
for(i=0;i<n;i++)
{
printf("%d \t", b[i]);
}
}

Output:

Main Menu
1.Create
2.Delete
3.Search
4.Insert
5.Display
6.Exit

Enter your Choice :1


11
Enter the number of nodes:3
Enter the Element:12
Enter the Element:11
Enter the Element:10

Do u want to continue::(y/n)y

Main Menu
1.Create
2.Delete
3.Search
4.Insert
5.Display
6.Exit

Enter your Choice :2


Enter the position u want to delete:1
The Elements are: 11 10

Do u want to continue::(y/n)y

Main Menu
1.Create
2.Delete
3.Search
4.Insert
5.Display
6.Exit

Enter your Choice :3


Enter the Element to be searched:10
Value 10 is in the list:

Do u want to continue::(y/n)y

Main Menu
1.Create
2.Delete
3.Search
4.Insert
5.Display

12
6.Exit

Enter your Choice :4


Enter the position u need to insert::1
Enter the element to insert:
12

The Elements of The list ADT are:12 11 10


Do u want to continue::(y/n)y

Main Menu
1.Create
2.Delete
3.Search
4.Insert
5.Display
6.Exit

Enter your Choice :5


The Elements of The list ADT are:12 11 10

Viva Questions

1. What is a data structure?


2. What is called as List?
3. Define array.
4. What are linear data structures?
5. What are the applications of List ADT?

Result:

Thus the program to implement list using array has been executed successfully.

13
Ex.No: 2
Date :
Singly Linked List

Aim:

To write a C program to implement singly linked list.

Description:

Linked list is a linear data structure. It is a collection of data elements, called nodes pointing to
the next node by means of a pointer. In linked list, each node consists of its own data and the address
of the next node and forms a chain.

Linked list contains a link element called first and each link carries a data item. Entry point into
the linked list is called the head of the list. Link field is called next and each link is linked with its
next link. Last link carries a link to null to mark the end of the list. Linked list is a dynamic data
structure. While accessing a particular item, start at the head and follow the references until you get
that data item.

Linked list is used while dealing with an unknown number of objects:

Linked list contains two fields - First field contains value and second field contains a link to the
next node. The last node signifies the end of the list that means NULL. The real life example of
Linked List is that of Railway Carriage. It starts from engine and then the coaches follow. Coaches
can traverse from one coach to other, if they connected to each other.

Algorithm:

Step1: Start the program.


Step2: Include the required header files at the top of the program.
Step3: Create a structure named node and declare variables to a node for singly linked list.
Step4: In the create () , check whether the head is NULL or not. If it is NULL, then get the
number of nodes from user and get data for each node that are created.
14
Step5: In the insert () check whether the head is NULL or not. If it is NOT NULL, the get the
position from user and then insert into list.
Step6: In the delete () , check whether the head is NULL or not. If it is NOT NULL, the get the
position to be delete from the user.
Step7: Insert and delete according to the position.
Step8: In display () , print the elements of singly linked list.
Step9: In main () method, use switch case statement to invoke the methods according to the
user choice entered.
Step10: End of the program

Code:

#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *link;
}*p,*pre;
struct node *head=NULL;
int pos,i;

void create()
{
int no;
printf("enter the no of nodes:");
scanf("%d",&no);
if(no>=1)
{
p=(struct node*)malloc(sizeof(struct node)); printf("enter the data1:");
scanf("%d",&p->data);
head=p;
for(i=1;i<no;i++)
{
pre=p;
p=(struct node*)malloc(sizeof(struct node));; pre->link=p;
printf("Enter the data %d :",i+1); scanf("%d",&p->data);
}
p->link=NULL;
printf("List Created...");
}

15
else
printf("Cannot create");
}

void insert()
{
if(head==0)
{
printf("* Cannot insert *");
}
else
{
printf("Enter the position:");
scanf("%d",&pos);
pre=head;
for(i=1;i<pos-1;i++)
{
pre=pre->link;
if(pre->link==NULL)
break;
}
if(pos>i+2||pos<1)
{
printf("*Position out of range");
}
else
{
p=(struct node*)malloc(sizeof(struct node)); printf("Enter the data:");
scanf("%d",&p->data);
if(pos==1)
{
p->link=head;
head=p;
}
else
{
p->link=pre->link;
pre->link=p;
}
printf("Data has been inserted.."); }
}
}
16
void del()
{
if(head==0)
{
printf("* Cannot delete * list is empty*");
}
else
{
printf("Enter the position:");
scanf("%d",&pos);
pre=head;
for(i=1;i<pos-1;i++)
{
pre=pre->link;
if(pre->link==NULL)
break;
}
p=pre->link;
if(pos>i+1||pos<1)
{
printf("\nPosition out of range");
}
else
{
if(pos==1)
{
head=head->link;
printf("Data has been deleted...");
}
else
{
pre->link=p->link;
printf("data has been deleted...");
}
}
}
}

void display()
{
printf("SINGLY LINKED LIST->");
17
p=head;
printf("%d",p->data);
while((p->link!=NULL)&&(head!=NULL))
{
printf("->");
p=p->link;
printf("%d",p->data);
}
}

void main()
{
int ch=0;
while(ch<5)
{
printf("\nSINGLY LINKED LIST MENU");
printf("\n1.Create\n2.Insert\n3.Delete\n4.Display\n5.Exit");
printf("\nEnter the choice:");
scanf("%d",&ch);
switch(ch)
{
case 1: create();
break;
case 2: insert();
break;
case 3: del();
break;
case 4: display();
break;
default:printf("* Exit ****");
}
}
}

Output:

SINGLY LINKED LIST MENU


1.Create
2.Insert
3.Delete
4.Display
5.Exit

18
Enter the choice:1
enter the no of nodes:3
enter the data 1:1
Enter the data 2 :2
Enter the data 3 :3
List Created...
SINGLY LINKED LIST MENU
1.Create
2.Insert
3.Delete
4.Display
5.Exit
Enter the choice:4
SINGLY LINKED LIST->1->2->3
SINGLY LINKED LIST MENU
1.Create
2.Insert
3.Delete
4.Display
5.Exit
Enter the choice:2
Enter the position:2
Enter the data:6
Data has been inserted..
SINGLY LINKED LIST MENU
1.Create
2.Insert
3.Delete
4.Display
5.Exit
Enter the choice:4
SINGLY LINKED LIST->1->6->2->3
SINGLY LINKED LIST MENU
1.Create
2.Insert
3.Delete
4.Display
5.Exit
Enter the choice:3
Enter the position:2
data has been deleted...
SINGLY LINKED LIST MENU
19
1.Create
2.Insert
3.Delete
4.Display
5.Exit
Enter the choice:4
SINGLY LINKED LIST->1->2->3
SINGLY LINKED LIST MENU
1.Create
2.Insert
3.Delete
4.Display
5.Exit
Enter the choice:5
* Exit ****

Viva Questions:

1. How many modifications are required to delete a node at the beginning?


2. How many modifications are required to insert a node in the middle of the linked list?
3. Which node contains NULL pointer in a single linked list?
4. Which node points to the first node in list?
5. How does array differ from linked list?

Result:

Thus the program to implement singly linked list has been executed successfully.

20
Ex.No: 3
Date : Stack ADT using Linked List

Aim:

To write a C program for Stack ADT using Linked list implementation.

Description:

A Stack is a linear data structure that serves as as collection of elements, with three main
operations: push, pop, and peek. In linked list implementation, a stack is a pointer to the head of the
list where pushing and popping items happens, with perhaps a counter to keep track of the list’s
size. The advantage of using a linked list over arrays is that it is possible to implement a stack that
can grow or shrink as much as needed.

In linked list implementation of a stack, every new element is inserted as 'top' element. That
means every newly inserted element is pointed by 'top'. Whenever we want to remove an element
from the stack, simply remove the node which is pointed by 'top' by moving 'top' to its previous
node in the list. The next field of the first element must be always NULL.

Algorithm:

Step1:Define a struct for each node in the stack. Each node in the stack contains data and
link to the next node. TOP pointer points to last node inserted in the stack.

Step2: The operations on the stack are


a. PUSH data into the stack
b. POP data out of stack

Step3:PUSH DATA INTO STACK


i. Enter the data to be inserted into stack.
ii. If TOP is NULL
1. The input data is the first node in stack.
2. The link of the node is NULL.
3. TOP points to that node.
iii. If TOP is NOT NULL
1. The link of TOP points to the new node.
2. TOP points to that node.

Step4:POP DATA FROM STACK


iv. If TOP is NULL
1. the stack is empty
v. If TOP is NOT NULL
1. The link of TOP is the current TOP.
2. The pervious TOP is popped from stack.

Step5:The stack represented by linked list is traversed to display its content.


21
Code:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
typedef struct node *ptrToNode;
typedef ptrToNode STACK;
typedef ptrToNode POSITION;

STACK Create(void)
{
STACK S;
S=(struct node*)malloc(sizeof(struct node));
if(S==NULL)
printf ("not created");
else
{
S->next=NULL;
printf("stack is created successfully");
}
return S;
}

int Isempty(STACK S)
{
return S->next==NULL;
}

void Push(int x, STACK S)


{
ptrToNode temp;
temp=(struct node*)malloc(sizeof(struct node));
if(temp==NULL)
printf("fatal error");
else
{
temp->data=x;
temp->next=S->next;
22
S->next=temp;
}
}

void Pop(STACK S)
{
ptrToNode first;
if(Isempty(S))
printf("no element to pop");
else
{
first=S->next;
S->next=S->next->next;
free(first);
}
}

void Display (STACK S)


{
S=S->next;
while(S!=NULL)
{
printf("\n%d",S->data);
S=S->next;
}
}

void main()
{
STACK S=NULL;
int n=0,i,c;
while(n<5)
{
printf("\n\n1.createStack\n2.push\n3.pop\n4.display\n5.exit\n");
printf("\n\nEnter the option:\t");
scanf("%d",&n);
switch(n)
{
case 1:
if(S==NULL)
S=Create();
else
23
printf("\n\nstack is already created");
break;
case 2:
if(S==NULL)
printf("\n\nstack is not created");
else
{
printf("enter the element:\t");
scanf("%d",&i);
Push(i,S);
}
break;
case 3:
if (S==NULL)
printf ("\n\nstack is not yet created");
else
Pop(S);
break;
case 4:
if(S==NULL)
printf("not created");
else
printf("\n the elements present in stack are:\n");
Display(S);
break;
default:
printf("\n\n........wrong entry.........");
}
}
}

Output:

1.createStack
2.push
3.pop
4.display
5.exit

Enter the option: 1


stack is created successfully

1.createStack
24
2.push
3.pop
4.display
5.exit

Enter the option: 2


enter the element: 12

1.createStack
2.push
3.pop
4.display
5.exit

Enter the option: 2


enter the element: 23

1.createStack
2.push
3.pop
4.display
5.exit

Enter the option: 4

the elements present in stack are:

23
12

1.createStack
2.push
3.pop
4.display
5.exit

Enter the option: 3

1.createStack
2.push
3.pop
4.display
5.exit

Enter the option: 4


the elements present in stack are:

12
25
1.createStack
2.push
3.pop
4.display
5.exit

Enter the option: 5

........wrong entry.........

Viva Questions:

1.How to remove an element from stack?


2.How to insert an element into a stack?
3.Is it possible to store any number of data elements in stack?
4.What are the demerits of stack?
5. What happens when you pop from an empty stack while implementing using the Stack ADT?

Result:

Thus the program for Stack ADT using Linked list implementation has been executed
successfully.

26
Ex.No: 4 Queue ADT using Linked List
Date :

Aim:
To write a C program for Queue ADT using Linked List implementation.

Description:

Queue is a linear data structure. Queue follows First In First Out (FIFO) methodology. The
element entered first in queue will leave first. Unlike Stack, Queue can be operated from both end.
Elements always enter from read and leaves from front of queue.
Following are the fundamental queue operations:
 enqueue : Add an element at the rear of the queue.
 dequeue : Removes an element from front of the queue.
 isEmpty : Returns if queue is empty.
 getFrontElement : Returns front element of queue without removing it from queue.

Algorithm:

Step1: Define a struct for each node in the queue. Each node in the queue contains data and
link to the next node. Front and rear pointer points to first and last node inserted in the
queue.
Step2: The operations on the queue are
a.INSERT data into the queue
b.DELETE data out of queue
Step3: INSERT DATA INTO queue
a).Enter the data to be inserted into queue.
b).If TOP is NULL
i).The input data is the first node in queue.
ii).The link of the node is NULL.
iii).TOP points to that node.
c).If TOP is NOT NULL
i).The link of TOP points to the new node.
ii).TOP points to that node.
Step4: DELETE DATA FROM queue
a).If TOP is NULL, the queue is empty
b). If TOP is NOT NULL
i).The link of TOP is the current TOP.
ii).The pervious TOP is popped from queue.
Step5: The queue represented by linked list is traversed to display its content.
27
Code:

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

struct node
{
int data;
struct node *link;
};
struct node *start=NULL;
struct node *temp,*nod, *front, *rear;
void insert_lnkq(struct node * );
void del_lnkq();
void display();

void main(void)
{
int opt;
do
{
printf("\nQueue - Linked List Implementaion\n");
printf("\n1.Enqueue\n");
printf("\n2.Dequeue\n");
printf("\n3.Display \n");
printf("\n4.Quit\n");
printf("\nEnter option: ");
scanf("%d",&opt);
switch(opt)
{
case 1:
nod=(struct node *)calloc(1,sizeof(struct node));
insert_lnkq(nod);
break;
case 2:
del_lnkq();
break;
case 3:
display();
break;

28
}
} while(opt<4);
}

void insert_lnkq(struct node *r) /* Insert operation*/


{
int item;
printf("\nEnter the element that has to be inserted: ");
scanf("%d",&item);
r->data=item;
r->link=0;
if(start==NULL)
{
start= r;
front =r;
rear=r;
}
else
{
rear->link= r;
rear =r;
printf("\nInserted....");
}
}

void del_lnkq() /* delete operation*/


{
if(start==NULL)
printf("\nQueue is empty! Deletion not possible!\n");
else
{
temp = start;
start = start->link;
front = start;
free(temp);
printf("Deleted....");
}
}

void display() /*display queue */


{
29
if(start == NULL)
printf("\n Queue is empty! \n");
else
{
printf("contents of the Queue: \n");
temp=start;
while(temp->link !=0)
{
printf("\n %d ",temp->data);
temp=temp->link;
}
printf("\n %d ",temp->data);
}
}
Output:
Queue - Linked List Implementaion
1.Enqueue
2.Dequeue
3.Display
4.Quit

Enter option: 1
Enter the element that has to be inserted: 12

Queue - Linked List Implementaion


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

Enter option: 1
Enter the element that has to be inserted: 67

Queue - Linked List Implementaion


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

Enter option: 3
contents of the Queue:
30
12
67

Queue - Linked List Implementaion


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

Enter option: 2
Deleted....

Queue - Linked List Implementaion


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

Enter option: 4

...Program finished with exit code 0


Press ENTER to exit console.

Viva Questions:

1. If the elements “A”, “B”, “C” and “D” are placed in a queue and are deleted one at a time, in
what order will they be removed?
2. When does a normal queue gets full if implemented using an array of size MAX_SIZE?
3. What is the term for inserting into a full queue known as?
4. What is the advantage of circular queue over linear queue?
5. How to check an empty queue?

Result:
Thus the program to implement Queue using linked list has been executed successfully.

31
Ex.No:5
Stack applications
Date :

Exercise 5 a) Conversion of decimal number into binary number

Aim:

To write a C program to convert the given decimal number into binary.

Description:

A decimal number can also be converted into its binary form. To convert a decimal number to
binary number, we need to divide the number by 2 until it reaches 0 or 1. And in each step, the
remainder are stored separately to form the binary equivalent number in reverse order.

Stack data structure follows the principle of LIFO (Last In First Out) . Stack allows push, pop,
peek operations to be performed. ... A decimal number can be converted into binary number using
the push and pop operation of the Stack.

“Divide by 2” uses a stack to keep track of the digits for the binary result. The Divide by 2
algorithm assumes that we start with an integer greater than 0. A simple iteration then continually
divides the decimal number by 2 and keeps track of the remainder.

Algorithm:

Step1: Start
Step2: Declare variables.
Step 3:Read a decimal number.
Step 4:Develop the procedure for conversion of different decimal number by modulus
and divide operator. Use modulo operator to find remainder and store in array
Step 5:Display the output by popping element from array.
Step 6:Stop

Code:

#include <stdio.h>
int main()
{
int a[10], number, i, j;
printf("\n Please Enter the Number You want to Convert : ");
scanf("%d", &number);

32
for(i = 0; number > 0; i++)
{
a[i] = number % 2;
number = number / 2;
}

printf("\n POP elements from stack ");


for(j = i - 1; j >= 0; j--)
{
printf(" %d ", a[j]);
}
printf("\n");
return 0;
}

Output:

Please Enter the Number You want to Convert : 23


POP elements from stack 1 0 1 1 1

Viva Questions:

1.What are the applications of stack?


2.How do u convert the decimal number into binary number?

Result:

Thus the program to convert the decimal number into binary number has been executed
successfully.

33
Exercise 5 b) Conversion of infix to post fix

Aim:

To write a C program to implement INFIX to POSTFIX expression.

Description:

One of the applications of Stack is in the conversion of arithmetic expressions in high- level
programming languages into machine readable form. An arithmetic expression may consist of
more than one operator and two operands e.g. (A+B)*C(D/(J+D)).These complex arithmetic
operations can be converted into polish notation using stacks which then can be executed in two
operands and an operator form.

Infix Expression:

Itfollows the scheme of <operand><operator><operand>i.e. an <operator> is preceded and


succeeded by an <operand>. Such an expression is termed infix expression. E.g.,A+B

Postfix Expression:

It follows the scheme of <operand><operand><operator>i.e. an <operator> is succeeded by


both the <operand>. E.g., AB+

Steps to convert Infix To Postfix

Let, X is an arithmetic expression written in infix notation. This algorithm finds the equivalent
postfix expression Y.

1. Push “(“onto Stack, and add “)” to the end ofX.

2. Scan X from left to right and repeat Step 3 to 6 for each element of X until the Stack is empty.

3. If an operand is encountered, add it to Y.

4. If a left parenthesis is encountered, push it onto Stack.

5. If an operator is encountered, then:

1. Repeatedly pop from Stack and add to Y each operator (on the top of Stack) which has the
same precedence as or higher precedence than operator.

2. Add operator to Stack.

6. If a right parenthesis is encountered, then:

34
1. Repeatedly pop from Stack and add to Y each operator (on the top of Stack) until a left
parenthesis is encountered.

2. Remove the left Parenthesis.

Algorithm:

Step1: Start the Program.


Step2: Get the Infix expression in array.
Step3: Check whether the expression contains the operand or operators.
Step4: Push the operand directly out of stack and the operator into the stack according to the
priority.
Step5: Increment top pointer for every push operation.
Step6: Conversion of postfix is based on the operator at the end of operands.
Step7: Print the POSTFIX expression
Step8: Stop the program.

Code:

#include<stdio.h>
#include<ctype.h>
char stack[100];
int top = -1;

void push(char x)
{
stack[++top] = x;
}

char pop()
{
if(top == -1)
return -1;
else
return stack[top--];
}

int priority(char x)
{
if(x == '(')
return 0;
if(x == '+' || x == '-')
return 1;
35
if(x == '*' || x == '/')
return 2;
return 0;
}

int main()
{
char exp[100];
char *e, x;
printf("Enter the expression : ");
scanf("%s",exp);
printf("\n");
e = exp;
while(*e != '\0')
{
if(isalnum(*e))
printf("%c ",*e);
else if(*e == '(')
push(*e);
else if(*e == ')')
{
while((x = pop()) != '(')
printf("%c ", x);
}
else
{
while(priority(stack[top]) >= priority(*e)) printf("%c ",pop());
push(*e);
}
e++;
}

while(top != -1)
{
printf("%c ",pop());
}
return 0;
}

36
Output:

Enter the expression : (A+B)*(C-D)

AB+CD-*

Viva Questions:

1. What is the output of the following expression: 2 3 4 5 + *-


2. What is the maximum difference between number of operators and operands?
3. What is the advantage of postfix expression?
4. Which expression doesn’t require parenthesis?
5. What is the output of the following expression: + * - 2 3 45

Result:

Thus the program to convert infix to postfix expression using Stack has been executed
successfully.

37
Ex.No: 6
Date : Insertion Sort

Aim:
To write a C program to implement insertion sort.

Description:

Insertion sort is an in-place comparison-based sorting algorithm. Here, a sub-list is


maintained which is always sorted. For example, the lower part of an array is maintained
to be sorted. An element which is to be inserted in this sorted sub-list, has to find its
appropriate place and then it has to be inserted there. Insertion sort is a simple sorting
algorithm that works the way we sort playing cards in our hands.

Algorithm:

Step 1: Start with an empty left hand [sorted array] and the cards face down on the table
[unsorted
array].
Step 2: Then remove one card [key] at a time from the table [unsorted array], and insert it into
the correct position in the left hand [sorted array].
Step 3: To find the correct position for the card, we compare it with each of the cards already in
the hand, from right to left.
Step 4: Stop
38
Code:

#include<stdio.h>
#include<conio.h>
void main()
{
int size, i, j, temp, list[100];
printf("Enter the size of the list: ");
scanf("%d", &size);
printf("Enter %d integer values: ", size);
for (i = 0; i < size; i++)
scanf("%d", &list[i]);
//Insertion sort logic
for (i = 1; i < size; i++)
{
temp = list[i];
j = i - 1;
while ((temp < list[j]) && (j >= 0))
{
list[j + 1] = list[j];
j = j - 1;
}
list[j + 1] = temp;
}
printf("List after Sorting is: ");
for (i = 0; i < size; i++)
printf(" %d", list[i]);
}

Output:

Enter the size of the list: 5


Enter 5 integer values: 34
32
89
45
11
List after Sorting is: 11 32 34 45 89

39
Viva Questions:

1. Which sorting algorithms in its typical implementation gives best performance when applied
on an array ?
2. Which sorting algorithm will take least time when all elements of input array are identical?
3.Mention the uses of insertion sort.
4. Consider an array of elements arr[5]= {5,4,3,2,1} , what are the steps of insertions done while
doing insertion sort in the array.
5.Why Sorting algorithms are important?

Result:

Thus the program to implement insertion sort has been executed successfully.

40
Ex.No: 7
Merge Sort
Date :

Aim:
To write a C program to implement the concept of merge sort.

Description:

Merge sort is a sorting algorithm that uses the divide, conquer, and combine
Algorithmic paradigm.

Divide means partitioning the n-element array to be sorted into two sub-arrays of
n/2 elements. If there are more elements in the array, divide A into two sub-arrays,
A1 and A2, each containing about half of the elements of A.

Conquer means sorting the two sub-arrays recursively using merge sort.
Combine means merging the two sorted sub-arrays of size n/2 to produce the sorted
array of n elements.

The basic steps of a merge sort algorithm are as follows:


a. If the array is of length 0 or 1, then it is already sorted.
b.Otherwise, divide the unsorted array into two sub-arrays of about half the size.
c.Use merge sort algorithm recursively to sort each sub-array.
d.Merge the two sub-arrays to form a single sorted list

Algorithm:
Step 1: Divide the unsorted list into two sublists of about half the size.
Step 2: Divide each of the two sublists recursively until we have list sizes of length 1,in
which case the list itself is returned.
Step 3: Merge the two sublists back into one sorted list.

Code:

#include<stdio.h>

void mergesort(int a[],int i,int j);


void merge(int a[],int i1,int j1,int i2,int j2);

int main()
{
int a[30],n,i;

41
printf("Enter no of elements:");
scanf("%d",&n);
printf("Enter array elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
mergesort(a,0,n-1);
printf("\nSorted array is :");
for(i=0;i<n;i++)
printf("%d ",a[i]);
return 0;
}

void mergesort(int a[],int i,int j)


{
int mid;
if(i<j)
{
mid=(i+j)/2;
mergesort(a,i,mid); //left recursion
mergesort(a,mid+1,j); //right recursion
merge(a,i,mid,mid+1,j); //merging of two sorted sub-arrays
}
}

void merge(int a[],int i1,int j1,int i2,int j2)


{
int temp[50]; //array used for merging
int i,j,k;
i=i1; //beginning of the first list
j=i2; //beginning of the second list
k=0;
while(i<=j1 && j<=j2) //while elements in both lists
{
if(a[i]<a[j])
temp[k++]=a[i++];
else
temp[k++]=a[j++];
}
while(i<=j1) //copy remaining elements of the first list
temp[k++]=a[i++];
while(j<=j2) //copy remaining elements of the second list
temp[k++]=a[j++];
42
//Transfer elements from temp[] back to a[]
for(i=i1,j=0;i<=j2;i++,j++)
a[i]=temp[j];
}

Output:

Enter no of elements:5
Enter array elements:
23
12
56
34
90

Sorted array is :12 23 34 56 90

Viva Questions:

1. Which technique Merge sort uses to implement sorting?


2. What is the average case time complexity of merge sort?
3. What is an array?
4. Write the application of sorting.
5. What are advantages and disadvantages of Bubble Sort?

Result:

Thus the program to implement merge sort has been implemented successfully.

43
Ex.No: 8
Quick Sort
Date :

Aim:

To write a C program to implement the concept of Quick sort.


Description:

Quick Sort, as the name suggests, sorts any list very quickly. Quick sort is not stable search, but it
is very fast and requires very less additional space. It is based on the rule of Divide and Conquer
(also called partition-exchange sort). This algorithm divides the list into three main parts:
 Elements less than the Pivot element
 Pivot element
 Elements greater than the pivot element
Algorithm:

Step 1: Pick an element, called a pivot, from the array.


Step 2: Partitioning: reorder the array so that all elements with values less than the pivot come
before the pivot, while all elements with values greater than the pivot come after it (equal
values can go either way). After this partitioning, the pivot is in its final position. This is
called the partition operation.
Step 3: Recursively apply the above steps to the sub-array of elements with smaller values
and separately to the sub-array of elements with greater values

Code:

void quicksort(int number[25],int first,int last)


{
int i, j, pivot, temp;
if(first<last)
{
pivot=first;
i=first;
j=last;
while(i<j)
{
while(number[i]<=number[pivot]&&i<last)
i++;
while(number[j]>number[pivot])
j--;
if(i<j)
44
{
temp=number[i];
number[i]=number[j];
number[j]=temp;
}
}
temp=number[pivot];
number[pivot]=number[j];
number[j]=temp;
quicksort(number,first,j-1);
quicksort(number,j+1,last);
}
}

int main()
{
int i, count, number[25];
printf("Enter some elements (Max. - 25): ");
scanf("%d",&count);
printf("Enter %d elements: ", count);
for(i=0;i<count;i++)
scanf("%d",&number[i]);
quicksort(number,0,count-1);
printf("The Sorted Order is: ");
for(i=0;i<count;i++)
printf(" %d",number[i]);
return 0;
}

Output:

Enter some elements (Max. - 25): 5


Enter 5 elements: 34
23
11
56
44
The Sorted Order is: 11 23 34 44 56

45
Viva Questions:

1. Differentiate STACK from ARRAY.


2. Write about quick sort performance.
3. Define sorting.
4. What do you mean by internal and external sorting.
5. List the difference between merge sort and quick sort

Result:

Thus the C program to implement the concept of Quick sort has been executed successfully.

46
Ex.No: 9
Insertion Operation in Binary Search Tree
Date :

Aim:
To write a C program to perform insertion operation in Binary Search tree.

Description:

A Binary Search Tree (BST) is a tree in which all the nodes follow the below mentioned
properties
 The left sub-tree of a node has a key less than or equal to its parent node's key.
 The right sub-tree of a node has a key greater than to its parent node's key.
 Thus, BST divides all its sub-trees into two segments; the left sub-tree and the right
sub-tree and can be defined as left_subtree (keys) ≤ node (key) ≤ right_subtree (keys)

BST is a collection of nodes arranged in a way where they maintain BST properties. Each node
has a key and an associated value. While searching, the desired key is compared to the keys in
BST and if found, the associated value is retrieved.

Algorithm:

Step 1: Declare function create (), search (), delete (), Display ().
Step 2: Create a structure for a tree contains left pointer and right pointer.
Step 3: Insert an element is by checking the top node and the leaf node and the operation will
be performed.
Step 4: Display the Tree elements.

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

struct treenode
{
int element;
struct treenode *left;
struct treenode *right;
};

typedef struct treenode *position,*searchtree;

searchtree insert(int x,searchtree t)


{
if(t==NULL)
{
t=(struct treenode*)malloc(sizeof(struct treenode));
if(t==NULL)
exit(0);
else
{
t->element=x;
t->left=t->right=NULL;
}
}
else
if(x<t->element)
t->left=insert(x,t->left);
else
if(x>t->element)
t->right=insert(x,t->right);
return t;
}

void intrav(searchtree head)


{
if(head==NULL)
return;
if(head->left!=NULL)
intrav(head->left);
printf("%d\t",head->element);
if(head->right!=NULL)
intrav(head->right);
}

void main()
{
int n,i,dat,ch;
searchtree t=NULL;
position node;
printf("Enter no of elements:\n");
scanf("%d",&n);
printf("Enter the elements:\n");
for(i=1;i<=n;i++)
{
scanf("%d",&dat);
t=insert(dat,t);
}
intrav(t);
do
{
printf("\n\n");
printf("\n ****BST-MENU****\n");
printf("\n 1 -> Insert a node\n");
printf("\n 2 -> Display(Inorder Traversal)\n");
printf("\n 3-> Exit\n");
printf("\nEnter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("\nEnter the element to be inserted:");
scanf("%d",&dat);
t=insert(dat,t);
break;

case 2: intrav(t);
break;
}
}while(ch<3);
}

Output:
Enter the number of elements:
5
Enter the elements:
6
1
8
9
2
1 2 6 8 9
***** BST-MENU****
1 -> Insert a node
2 -> Display(Inorder Traversal)
3 -> Exit
Enter your choice :1
Enter the element to be inserted : 5
***** BST-MENU****
1 -> Insert a node
2 -> Display(Inorder Traversal)
3 -> Exit
Enter your choice :2
1 2 5 6 8 9

Viva Questions:

1.Write the various operation performed in the binary search tree?


2. How many nodes will be there in given nth level?
3. Write the necessary condition for inserting element into BST
4. How will you find the maximum and minimum element in BST?
5. How will you perform deletion in BST with 2 children

Result:

Thus the C program to perform insertion operation on binary search tree has been executed
successfully.
Ex.No: 10
Tree Traversals
Date :

Aim:
To write a C program to implement tree traversals using linked list.

Description:
Traversal is a process to visit all the nodes of a tree and may print their values too. Because, all
nodes are connected via edges (links) we always start from the root (head) node. That is, we
cannot random access a node in a tree. There are three ways which we use to traverse a tree −
 In-order Traversal
Steps
1. Traverse the left sub-tree (keep visit the left sub tree until you reach leaf node).
2. Visit the current node.
3. Traverse the left sub-tree.

 Pre-order Traversal
Steps
1. Visit the root node
2. traverse the left sub-tree in pre-order
3. traverse the right sub-tree in pre-order

 Post-order Traversal

Steps
1. Traverse the left sub tree.
2. Traverse the right sub tree.
3. Visit the node

Algorithm:

Step 1: Start the program


Step 2: Declare the structure for node
Step 3: Declare all variables
Step 4: Use create() to create a tree
Step 5: Use insert() to insert elements into the tree
Step6: Recursively apply pre-order, post-order and in-order
Step 7: Display the nodes
Step 8: Stop

Code:
#include<stdio.h>
#include<stdlib.h>
struct btree
{
struct btree *lchild;
int val;
struct btree *rchild;
} *t, *temp,*temp1,*last;
int element,n,flag;
int a[100];
int i=1,in[50];
void inorder (struct btree*);
void preorder (struct btree*);
void postorder (struct btree*);
struct btree *create (struct btree*, int);
struct btree *insert (struct btree*, int,int);
void find(struct btree*,int);
void main( )
{
int ch,m,c;
n=0;
printf ("\n\n\t Binary tree");
do
{
printf ("\nMain Menu\n");
printf ("\n1.create \n2.Insert \n3.Inorder\n4.Preorder \n5.Postorder\n6.exit"); printf ("\nEnter your
choice:");
scanf ("%d", &ch);
switch(ch)
{
case 1:
printf ("Enter the element\n");
scanf ("%d", &element);
t = create (t, element);
last = t;
n++;
break;
case 2:
printf ("Enter the element\n");
scanf("%d",&element);
n++;
m =n;
c=-1;
while(m>1)
{
c++;
a[c] = m%2;
m=m/2;
}
t = insert (t, element,c);
break;
case 3:
printf ("Inorder traversal:");
inorder(t);
break;
case 4:
printf ("Preorder traversal:");
preorder(t);
break;
case 5:
printf ("Postorder traversal:");
postorder(t);
break;
}
}
while(ch != 6);
}
struct btree *create (struct btree* t, int element) {
t = (struct btree*) malloc (sizeof(struct btree)); t->val = element;
t->lchild = NULL;
t->rchild = NULL;
return t;
}

struct btree *insert (struct btree* t, int element,int c) {


if (c == 0)
{
temp = (struct btree*) malloc (sizeof(struct btree)); last = temp;
temp->val = element;
temp->lchild = NULL;
temp->rchild = NULL;
if(a[c] == 0)
t->lchild = temp;
else
t->rchild = temp;
return t;
}
else if(a[c] == 0)
{
t->lchild = insert(t->lchild, element,c-1); }
else if (a[c] == 1)
{
t->rchild = insert (t->rchild, element,c-1); }
return t;
}
void inorder (struct btree *t)
{
if (t == NULL)
return;
else
{
inorder (t->lchild);
printf("%d ",t->val);
in[i]=t->val;
i++;
inorder (t->rchild);
}
}
void preorder (struct btree *t)
{
if (t == NULL)
return;
else
{
printf("%d ",t->val);
preorder (t->lchild);
preorder (t->rchild);
}
}
void postorder (struct btree *t)
{
if (t == NULL)
return;
else
{
postorder (t->lchild);
postorder (t->rchild);
printf("%d ",t->val);
}
}
Output:
Binary tree
Main menu
1. Create
2. Insert
3. Inorder
4. Preorder
5. Postorder
6. Exit
Enter your choice :1
Enter the element
5
Binary tree
Main menu
1.Create
2.Insert
3.Inorder
4.Preorder
5.Postorder
6.Exit
Enter your choice :2
Enter the element
6
Binary tree
Main menu
1.Create
2.Insert
3.Inorder
4.Preorder
5.Postorder
6.Exit
Enter your choice :2
Enter the element
4
Binary tree
Main menu
1.Create
2.Insert
3.Inorder
4.Preorder
5.Postorder
6.Exit
Enter your choice :3
Inorder traversal : 6 5 4

Viva Questions:

1.What are the data structures used for Binary Trees?


2. Explain implementation of traversal of a binary tree.
3. How to perform insertion into a binary tree.
4. Define post-order traversal.
5. Define in-order traversal.

Result:

Thus the C program to implement tree traversals using linked list has been executed
successfully.
Ex.No: 11
Hashing with collision resolution
Date :
Aim:

To write a C program to implement hashing with collision resolution.

Description:

Hashing is a technique to convert a range of key values into a range of indexes of an array.
We're going to use modulo operator to get a range of key values. Consider an example of hash
table of size 20, and the following items are to be stored. Item are in the (key,value) format.The
collision problem can be solved by using linear probing method.
(1,20)
(2,70)
(42,80)
(4,25)
(12,44)
(14,32)
(17,11)
(13,78)
(37,98)

Sr.No. Key Hash Array Index


1 1 1 % 20 = 1 1
2 2 2 % 20 = 2 2
3 42 42 % 20 = 2 2
4 4 4 % 20 = 4 4
5 12 12 % 20 = 12 12
6 14 14 % 20 = 14 14
7 17 17 % 20 = 17 17
8 13 13 % 20 = 13 13
9 37 37 % 20 = 17 17

Algorithm:

Step 1: Create a structure, data (hash table item) with key and value as data.
Step 2: Now create an array of structure, data of some certain size (10, in this case). But, the size
of array must be immediately updated to a prime number just greater than initial array capacity
(i.e 10, in this case).
Step 3: A menu is displayed on the screen.
56
Step 4: User must choose one option from four choices given in the menu
Step 5: Perform all the operations
Step 6: Stop the program

Code:

#include<stdio.h>
#include<stdlib.h>
struct hash
{
struct hashnode *ptr;
};

struct hashnode
{
int val;
struct hashnode *next;
};

struct hash *create_hash(int size)


{
struct hash *htable;
int i;
htable = (struct hash *) malloc(sizeof(struct hash) * size);
if (htable == NULL)
{
printf("\n Out of Memory !!");
return NULL;
}
for (i = 0; i < size; i++)
htable[i].ptr = NULL;
return htable;
}

struct hashnode *create_hashnode(int val)


{
struct hashnode *tmp;
tmp = (struct hashnode *) malloc(sizeof(struct hashnode));
if (tmp == NULL)
printf("\n System out of Memory");
tmp->next = NULL;
tmp->val = val;
57
}

int insert_value(struct hash **htable, int val, int hsize)


{
int slot;
struct hash *htptr = (*htable);
struct hashnode *tmp;
if ((*htable) == NULL)
{
printf("\n Hash Table is not created");
return 0;
}
slot = (val) % hsize;
if (htptr[slot].ptr == NULL) {
tmp = create_hashnode(val);
htptr[slot].ptr = tmp;
}
else
{
tmp = create_hashnode(val);
tmp->next = htptr[slot].ptr;
htptr[slot].ptr = tmp;
}
return 1;
}

void print_hashtable(struct hash **htable, int size)


{
int i;
struct hashnode *tmp;
struct hash *htmp = (*htable);
for (i = 0; i < size; i++)
{
tmp = htmp[i].ptr;
while (tmp != NULL) {
printf(" %d ", tmp->val);
tmp = tmp->next;
}
printf("\n");
}
}
58
int seach_hashtable(struct hash **htable, int val, int size)
{
int slot, found = 0;
slot = val % size;
struct hashnode *tmp;
tmp = (*htable)[slot].ptr;
while (tmp != NULL)
{
if (tmp->val == val)
{
found = 1;
break;
}
tmp = tmp->next;
}
return found;
}

int main()
{
struct hash *hashtable1;
int hashtable1size;
printf("\n Enter the size of HashTable : ");
scanf("%d", &hashtable1size);
hashtable1 = create_hash(hashtable1size);
if (hashtable1 != NULL)
printf("\nTable Created Successfully !!");
int key, val, found;
do {
printf("\n Hash Table Collision Resolution ");
printf("\n 1. Insert value ");
printf("\n 2. Search Value");
printf("\n 3. Print Table");
printf("\n 4. Exit");
printf("\n Enter the key [1-4] :");
scanf("%d", &key);
switch (key) {
case 1:
printf("\n Enter Val : ");
59
scanf("%d", &val);
insert_value(&hashtable1, val, hashtable1size);
break;
case 2:
printf("\n Enter Val : ");
scanf("%d", &val);
found = seach_hashtable(&hashtable1, val, hashtable1size);
if (found == 0)
printf("\n Val not found");
else
printf("\n %d found at slot %d ", val,
val % hashtable1size);
break;
case 3:
print_hashtable(&hashtable1, hashtable1size);
break;
case 4:
printf("\n Thank you !!! ");
break;
default:
break;
}
} while (key != 4);
return 0;
}

Output:

Enter the size of HashTable : 3

Table Created Successfully !!


Hash Table Collision Resolution
1. Insert value
2. Search Value
3. Print Table
4. Exit
Enter the key [1-4] :1

Enter Val : 12

Hash Table Collision Resolution


1. Insert value
2. Search Value
60
3. Print Table
4. Exit
Enter the key [1-4] :1

Enter Val : 45

Hash Table Collision Resolution


1. Insert value
2. Search Value
3. Print Table
4. Exit
Enter the key [1-4] :1

Enter Val : 67

Hash Table Collision Resolution


1. Insert value
2. Search Value
3. Print Table
4. Exit
Enter the key [1-4] :3
45 12
67

Hash Table Collision Resolution


1. Insert value
2. Search Value
3. Print Table
4. Exit
Enter the key [1-4] :2

Enter Val : 67

67 found at slot 1
Hash Table Collision Resolution
1. Insert value
2. Search Value
3. Print Table
4. Exit
Enter the key [1-4] :4

61
Viva Questions:

1. If several elements are competing for the same bucket in the hash table, what is it called?
2. How to insert a node in hash table?
3. What is sizeof() function?
4. How to delete a node from hash table.
5. What is hash function?
6. What is index?

Result:

Thus the C program to implement hashing with collision resolution has been executed
successfully.

62
Ex.No: 12 Dijkstra’s Shortest Path Algorithm
Date :

Aim:

To write a C program to implement Dijkstra’s Shortest Path Algorithm.

Description:

Dijkstra's algorithm has many variants but the most common one is to find the shortest paths
from the source vertex to all other vertices in the graph.

Steps:
 Set all vertices distances = infinity except for the source vertex, set the source distance=
0.
 Push the source vertex in a min-priority queue in the form (distance , vertex), as the
comparison in the min-priority queue will be according to vertices distances.
 Pop the vertex with the minimum distance from the priority queue (at first the popped
vertex =source).
 Update the distances of the connected vertices to the popped vertex in case of "current
vertex distance + edge weight < next vertex distance", then push the vertex with the new
distance to the priority queue.
 If the popped vertex is visited before, just continue without using it.
 Apply the same algorithm again until the priority queue is empty.

Algorithm:

Step 1:Select the source node also called the initial node
Step 2: Define an empty set N that will be used to hold nodes to which a shortest path has been
found.
Step 3: Label the initial node with , and insert it into N.
Step 4: Repeat Steps 5 to 7 until the destination node is in N or there are no more labelled nodes
in N.
Step 5: Consider each node that is not in N and is connected by an edge from the newly inserted
node.
Step 6. (a) If the node that is not in N has no label then SET the label of the node = the label of
the newly inserted node + the length of the edge.
(b) Else if the node that is not in N was already labelled, then SET its new label =
minimum
Step 7: Pick a node not in N that has the smallest label assigned to it and add it to N.

63
Code:

#include<stdio.h>
#include<conio.h>
#define infinity 999
void dij(int n,int v,int cost[10][10],int dist[])
{
int i,u,count,w,flag[10],min;
for(i=1;i<=n;i++)
{ flag[i]=0;
dist[i]=cost[v][i];
}
count=2;
while(count<=n)
{
min=99;
for(w=1;w<=n;w++)
if(dist[w]<min && !flag[w])
{ min=dist[w];
u=w; }
flag[u]=1;
count++;
for(w=1;w<=n;w++)
if((dist[u]+cost[u][w]<dist[w]) && !flag[w])
dist[w]=dist[u]+cost[u][w];
}
}

void main()
{
int n,v,i,j,cost[10][10],dist[10]; clrscr();
printf("\n Enter the number of nodes:");
scanf("%d",&n);
printf("\n Enter the cost matrix:");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
cost[i][j]=infinity;
64
}
printf("\n Enter the source node:");
scanf("%d",&v);
dij(n,v,cost,dist);
printf("\n Shortest path:\n");
for(i=1;i<=n;i++)
if(i!=v)
printf("%d->%d,cost=%d\n",v,i,dist[i]);
}

Output:

Enter the number of nodes:3

Enter the cost matrix:0 4 6


304
650

Enter the source matrix:1

Shortest path:
1->2,cost=4
1->3,cost=6

Viva Questions:

1. How to find the adjacency matrix?


2. Which algorithm solves the single pair shortest pathproblem?
3. How to find shortest distance from source vertex to targetvertex?
4. What is the maximum possible number of edges in a directed graph with no self loops having
8vertices?
5. Does Dijkstra’s Algorithm work for both negative and positive weights?

Result:

Thus the C program to implement Dijkstra’s Shortest Path Algorithm has been executed
successfully.

65

You might also like