Dsa Manual Final
Dsa Manual Final
Dsa Manual Final
Faculty of Engineering
Department of Computer Science and
Engineering
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.
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.
5) Students must use pen for writing and pencil to draw Flowchart in Work book.
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.
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
4
List of Experiments
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 Today's most popular Linux OS and RDBMS MySQL have been written in C.
7
Ex.No: 1
List Using Arrays
Date :
Aim:
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
Do u want to continue::(y/n)y
Main Menu
1.Create
2.Delete
3.Search
4.Insert
5.Display
6.Exit
Do u want to continue::(y/n)y
Main Menu
1.Create
2.Delete
3.Search
4.Insert
5.Display
6.Exit
Do u want to continue::(y/n)y
Main Menu
1.Create
2.Delete
3.Search
4.Insert
5.Display
12
6.Exit
Main Menu
1.Create
2.Delete
3.Search
4.Insert
5.Display
6.Exit
Viva Questions
Result:
Thus the program to implement list using array has been executed successfully.
13
Ex.No: 2
Date :
Singly Linked List
Aim:
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 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:
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:
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:
Result:
Thus the program to implement singly linked list has been executed successfully.
20
Ex.No: 3
Date : Stack ADT using Linked List
Aim:
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.
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 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 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
1.createStack
24
2.push
3.pop
4.display
5.exit
1.createStack
2.push
3.pop
4.display
5.exit
1.createStack
2.push
3.pop
4.display
5.exit
23
12
1.createStack
2.push
3.pop
4.display
5.exit
1.createStack
2.push
3.pop
4.display
5.exit
12
25
1.createStack
2.push
3.pop
4.display
5.exit
........wrong entry.........
Viva Questions:
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);
}
Enter option: 1
Enter the element that has to be inserted: 12
Enter option: 1
Enter the element that has to be inserted: 67
Enter option: 3
contents of the Queue:
30
12
67
Enter option: 2
Deleted....
Enter option: 4
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 :
Aim:
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;
}
Output:
Viva Questions:
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:
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:
Postfix Expression:
Let, X is an arithmetic expression written in infix notation. This algorithm finds the equivalent
postfix expression Y.
2. Scan X from left to right and repeat Step 3 to 6 for each element of X until the Stack is empty.
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.
34
1. Repeatedly pop from Stack and add to Y each operator (on the top of Stack) until a left
parenthesis is encountered.
Algorithm:
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:
AB+CD-*
Viva Questions:
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:
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:
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.
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>
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;
}
Output:
Enter no of elements:5
Enter array elements:
23
12
56
34
90
Viva Questions:
Result:
Thus the program to implement merge sort has been implemented successfully.
43
Ex.No: 8
Quick Sort
Date :
Aim:
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:
Code:
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:
45
Viva Questions:
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;
};
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:
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:
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;
}
Viva Questions:
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:
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)
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;
};
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 Val : 12
Enter Val : 45
Enter Val : 67
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:
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:
Shortest path:
1->2,cost=4
1->3,cost=6
Viva Questions:
Result:
Thus the C program to implement Dijkstra’s Shortest Path Algorithm has been executed
successfully.
65