DS Lab

You might also like

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 74

EASWARI ENGINEERING COLLEGE

(Autonomous)
RAMAPURAM, CHENNAI-89

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

LAB MANUAL

REGULATIONS 2019

191CSC311L- DATA STRUCTURES LABORATORY IN C

ACADEMIC YEAR:2022-2023

B.E-CSE II YEAR/ III SEMESTER

Prepared By Approved By

Mrs.A.Jeba Sheela / AP HOD/CSE


191CSC311L DATA STRUCTURES LABORATORY IN C

LT PRC 0 0 4 02

COURSE OBJECTIVES

1. To understand and implement Linear data structures using C


2. To implement Non Linear data structures using C
3. To Implement of Graph and Traversal algorithms
4. To implement Searching and Sorting algorithms
5. To implement Hashing techniques

LIST OF EXPERIMENTS

1. Array implementation of List ADT


2. Array implementation of Stacks
3. Array implementation of Queues
4. Linked list implementation of List ADT
5. Linked list implementation of Stacks
6. Linked list implementation of Queues
7. Application of Stacks and Queues
8. Implementation of Binary Search Trees and Traversal
9. Implementation of AVL Trees
10. Implementation of Heaps using Priority Queues
11. Implementation of Graph and Traversal algorithms
12. Implementation of Sorting Algorithms : Bubble sort & Quick sort
13. Implementation of Linear search and Binary search
14. Implementation of Hashing - any one collision resolution techniques

TOTAL:60 PERIODS
COURSE OUTCOMES:

Upon the completion of the course the students should be able to:

CO1: Implement Linear Data Structure programs in C


CO2: Implement Non-linear Data Structure programs in C
CO3: Implement of Graph and Traversal algorithms
CO4: Implement searching and sorting algorithms
CO5: Implement Hashing techniques
TABLE OF CONTENTS

Ex.No. Date Title of the Experiment Page No. Signature

1 Array implementation of List ADT

2 Array implementation of Stacks

3 Array implementation of Queues

4 Linked list implementation of List ADT

5 Linked list implementation of Stacks

6 Linked list implementation of Queues

7.a Application of Stacks

7.b Application of Queues

8 Implementation of Binary Search Trees and Traversal

9 Implementation of AVL Trees

10 Implementation of Heaps using Priority Queues

11 Implementation of Graph and Traversal algorithms

12.a Implementation of Sorting Algorithms : Bubble sort

12.b Implementation of Sorting Algorithms : Quick sort

13.a Implementation of Linear search

13.b Implementation of Binary search

14 Implementation of Hashing - any one collision


resolution techniques

CONTENT BEYOND SYLLABUS

15 Applications of Graphs – Dijikstra’s Algorithm

16 Implementation of Radix Sort


‘C’PROGRAMMING

C is a powerful, portable and elegantly structured programming language.It combines features


of a high-level language with the elements of an assembler and therefore,suitable for writing both
system software and application packages.It is the most widely used general- purpose language today.
C has been used for implementing systems such as operating systems, compilers, linkers, word
processors and utility packages.It is a robust language whose rich set of built-in functions and
operators can be used to write any complex program.Programs written in C are fast and efficient.

TurboCIDE

Turbo C IDE facilitates editing, debugging and execution of applications written in C.C
programs are saved with .c extension.Some of the short cut keys are:

Ctrl+F1 Help
F2 Save
F3 Open
Copy Ctrl+Ins
Cut Shift+Del
Paste Shift+Ins
Clear Ctrl+Del
Alt+F9 Compile
Ctrl+F9 Execute
Alt+F5 UserScreen
F7 TraceInto
Alt+F3 Close
Alt+X Quit
Ex NO: 1

DATE : ARRAY IMPLEMENTATION OF LIST ADT

Aim
To write a ‘C’ program to implement List ADT using arrays.
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: In Insertion, half of the elements to be shifted upwards and in deletion, half of the elements to
be shifted downwards.
Step 5: Display the output using an array.
Step 6: Stop the program execution.
Program

#include<stdio.h>
#include<conio.h>
#define MAX 10
void create();
void insert();
void deletion();
void search();
void display();

int a,b[20], n, p, e, f, i, pos;

void main()
{
clrscr();
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;
case 6: exit(); break;
default: printf("\n Enter the correct choice:");
}
printf("\n Do u want to continue:::");
scanf("\n%c", &g);
}
while(g=='y'||g=='Y');
getch();
}

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

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

printf("\n The Elements after deletion");


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

void search()
{
printf("\n Enter the Element to be searched:");
scanf("%d", &e);
for(i=0;i<n;i++)
{

if(b[i]==e)
{
printf("Value is in the %d Position", i);
}

else
{
printf("Value %d is not in the list::", e);
continue;
}
}
}
void insert()
{
printf("\n Enter the position u need to insert::");
scanf("%d", &pos);
if(pos>=n)
{
printf("\n invalid Location::");
}
else
{
for(i=MAX-1;i>=pos-1;i--)
{
b[i+1]=b[i];
}
printf("\n Enter the element to insert::\n");
scanf("%d",&p);
b[pos]=p;
n++;
}
printf("\n The list after insertion::\n");
display();
}
void display()
{
printf("\n The Elements of The list ADT are:");
for(i=0;i<n;i++)
{
printf("\n\n%d", b[i]);
}
}
Output

Result

Thus, the ‘C’ program to implement the list ADT using arrays has been executed and the output is verified
successfully.
Ex NO: 2
ARRAY IMPLEMENTATION OF STACK
DATE :

Aim

To write a ‘C’ program to implement stack using arrays

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: In Insertion, half of the elements to be shifted upwards and in deletion , half of the elements to
be shifted downwards.
Step 5: Display the output using an array.
Step 6: Stop

Program

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

int n, top = -1, *stack;

void push(int x){


if(top==n) return;
stack[++top]=x;
}

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

int peek(){
if(top==-1) return -1;
return stack[top];
}

void display(){
for(int i=top ; i>-1 ; i--) printf("%d ",stack[i]);
printf("\n\n");
}

int main(){
n = 10;

printf("Initializing the stack with size 10\n\n");

stack = (int*)malloc(n*sizeof(int));

printf("Pushing elements into the stack\n1\n2\n3\n\n");

push(1);
push(2);
push(3);

printf("Displaying elements of the stack -\n");

display();

printf("The top of the stack = %d\n\n",peek());

printf("Pop the top of the stack = %d\n\n",pop());

printf("Pop the top of the stack = %d\n\n",pop());

printf("Displaying elements of the stack -\n");

display();

return 0;
}
Output
Initializing the stack with size 10

Pushing elements into the stack


1
2
3

Displaying elements of the stack -


3 2 1

The top of the stack = 3

Pop the top of the stack = 3

Pop the top of the stack = 2

Displaying elements of the stack -


1
Result

Thus the ‘C’ program to implement stack using arrays is executed and the output is verified
successfully.
Ex NO: 3
ARRAY IMPLEMENTATION OF QUEUE
DATE :

Aim

To write a ‘C’ program to implement queue using arrays.

Algorithm

Step1:Define a array which stores queue elements.


Step2:The operations on the queue are
a)INSERT data into the queue
b)DELETE data out of queue
step3:INSERT DATA INTO queue
3a.Enter the data to be inserted into queue.
3b.If TOP is NULL then the input data is the first node in queue.
the link of the node is NULL.TOP points to that node.
3c.If TOP is NOT NULL thenthe link of TOP points to the new node.TOP points to that node.
Step4:DELETE DATA FROM queue
4a.If TOP is NULL then the queue is empty
4b.If TOP is NOT NULL then the link of TOP is the current TOP.The pervious TOP is popped
from queue.
Step 5: The queue represented by linked list is traversed to display its content.
Program
#include<conio.h>
#include<stdio.h>
#define max 5
int queue[max],front=0,rear=0;
int menu();
void enqueue();
void dequeue();
void display();
void main()
{
int ch;
clrscr();
printf("\nProgrammingUnit.com - Free Source Codes\n");
printf("\nQueues using Arrays\n");
do
{ ch=menu();
switch(ch)
{
case 1: enqueue(); break;
case 2: dequeue(); break;
case 3: display(); break;
case 4: exit(); break;
default: printf("\n Please enter a valid choice!!");
}
}while(1);
}
int menu()
{
int ch;
printf("\n1.ENQUEUE \n2.DEQUEUE \n3.DISPLAY \n4.EXIT");
printf("\nEnter your Choice:");
scanf("%d",&ch);
return ch;
}
void enqueue()
{
int element;
if(rear==max)
{
printf("\nOverflow!!");
}
else
{
printf("\nEnter Element:");
scanf("%d",&element);
queue[rear++]=element;
printf("\n %d Enqueued at %d",element,rear);
}
}
void dequeue()
{
if(rear==front)
{
printf("\nUnderflow!!");
}
else
{
front++;
printf("\nElement is Dequeued from %d",front);
}
}
void display()
{
int i;
if(front==rear)
{
printf("\nQueue is Empty!!!");
}
else
{
printf(" \n");
for(i=front;i<max;i++)
{
printf(" | %d ",queue[i]);
}
printf("|");
}
}
Output

Queue using Array

1.Insertion
2.Deletion
3.Display
4.Exit

Enter the Choice:1


Enter no 1:10

Enter the Choice:1


Enter no 2:54

Enter the Choice:1


Enter no 3:98

Enter the Choice:1


Enter no 4:234

Enter the Choice:3

Queue Elements are:


10
54
98
234
Result
Thus, the ‘C ‘ program to implement the queue using array has been executed and the output is
verified successfully.
Ex NO: 4
LINKED LIST IMPLEMENTATION OF LIST
DATE :

Aim
To write a program to implement the linked list using pointers.

Algorithm

Step 1: Start
Step 1: Include all the header files which are used in the program.
Step 2: Declare all the user defined functions.
Step 3: Define a Node structure with two members data and next
Step 4: Define a Node pointer 'head' and set it to NULL.
Step 4: Implement the main method by displaying operations menu and make suitable function calls in
the main method to perform user selected operation.
Step 6: Stop

Insertion

In a single linked list, the insertion operation can be performed in three ways. They are as follows...
 Inserting At Beginning of the list
 Inserting At End of the list
 Inserting At Specific location in the list
 Inserting At Beginning of the list

The following steps to insert a new node at beginning of the single linked list...

Step 1: Create a newNode with given value.


Step 2: Check whether list is Empty (head == NULL)
Step 3: If it is Empty then, set newNode→next = NULL and head = newNode.
Step 4: If it is Not Empty then, set newNode→next =head and head=newNode

Inserting At End of the list

The following steps to insert a new node at end of the single linked list...

Step 1: Create a newNode with given value and newNode → next as NULL.
Step 2: Check whether list is Empty (head == NULL).
Step 3: If it is Empty then, set head = newNode.
Step 4: If it is Not Empty then, define a node pointer temp and initialize with head.

Step 5: Keep moving the temp to its next node until it reaches to the last nodein the list (until
temp → next is equal to NULL).
Step 6: Set temp → next = newNode.

Inserting At Specific location in the list (After a Node)


The following steps to insert a new node after a node in the single linked list...

Step 1: Create a newNode with given value.


Step 2: Check whether list is Empty (head == NULL)
Step 3: If it is Empty then, set newNode → next = NULL and head = newNode.
Step 4: If it is Not Empty then, define a node pointer temp and initialize with head.
Step 5: Keep moving the temp to its next node until it reaches to the nodeafter which we want to insert
the newNode (until temp1 → data isequal to location, here location is the node value after which
we want to insert the newNode).
Step 6: Every time check whether temp is reached to last node or not. If it isreached to last node then
display 'Given node is not found in the list!!! Insertion not possible!!!' and terminate the
function. Otherwise movethe temp to next node.
Step 7: Finally, Set 'newNode → next = temp → next' and 'temp → next =newNode'

Deletion
In a single linked list, the deletion operation can be performed in three ways. They are as follows...
 Deleting from Beginning of the list
 Deleting from End of the list
 Deleting a Specific Node
 Deleting from Beginning of the list

The following steps to delete a node from beginning of the single linked list...

Step 1: Check whether list is Empty (head == NULL)


Step 2: If it is Empty then, display 'List is Empty!!! Deletion is not possible' and terminate the function.
Step 3: If it is Not Empty then, define a Node pointer 'temp' and initialize with head.
Step 4: Check whether list is having only one node (temp → next == NULL)
Step 5: If it is TRUE then set head = NULL and delete temp (Setting Empty listconditions)
Step 6: If it is FALSE then set head = temp → next, and delete temp.

Deleting from End of the list


We can use the following steps to delete a node from end of the single linked list...

Step 1: Check whether list is Empty (head == NULL)


Step 2: If it is Empty then, display 'List is Empty!!! Deletion is not possible' andterminate the function.
Step 3: If it is Not Empty then, define two Node pointers 'temp1' and 'temp2'and initialize 'temp1' with
head.
Step 4: Check whether list has only one Node (temp1 → next == NULL)
Step 5: If it is TRUE. Then, set head = NULL and delete temp1. And terminatethe function.
(Setting Empty list condition)
Step 6: If it is FALSE. Then, set 'temp2 = temp1 ' and move temp1 to its next node. Repeat the same
until it reaches to the last node in the list(until temp1 → next == NULL)
Step 7: Finally, Set temp2 → next = NULL and delete temp1.

Deleting a Specific Node from the list

The following steps to delete a specific node from the single linked list...

Step 1: Check whether list is Empty (head == NULL)


Step 2: If it is Empty then, display 'List is Empty!!! Deletion is not possible' and terminate the function.
Step 3: If it is Not Empty then, define two Node pointers 'temp1' and 'temp2'and initialize 'temp1' with
head.
Step 4: Keep moving the temp1 until it reaches to the exact node to be deleted or to the last node. And
every time set 'temp2 = temp1' beforemoving the 'temp1' to its next node.
Step 5: If it is reached to the last node then display 'Given node not found in the list! Deletion not
possible!!!'. And terminate the function.
Step 6: If it is reached to the exact node which we want to delete, then checkwhether list is having only
one node or not
Step 7: If list has only one node and that is the node to be deleted, then sethead = NULL and delete
temp1 (free(temp1)).
Step 8: If list contains multiple nodes, then check whether temp1 is the first node in the list
(temp1 == head).
Step 9: If temp1 is the first node then move the head to the next node (head =head → next) and delete
temp1.
Step 10: If temp1 is not first node then check whether it is last node in the list(temp1 → next ==NULL).
Step 11: If temp1 is last node then set temp2 → next = NULL and deletetemp1 (free(temp1)).
Step 12: If temp1 is not first node and not last node then set temp2 → next = temp1 → next and delete
temp1 (free(temp1)).

Displaying a Single Linked List

The following steps to display the elements of a single linked list...

Step 1: Check whether list is Empty (head == NULL)


Step 2: If it is Empty then, display 'List is Empty!!!' and terminate the function.
Step 3: If it is Not Empty then, define a Node pointer 'temp' and initialize with head.
Step 4: Keep displaying temp → data with an arrow (--->) until temp reaches to the last node
Step 5: Finally display temp → data with arrow pointing to NULL (temp → data---> NULL).
Program

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

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

struct node *start = NULL;


void insert_at_begin(int);
void insert_at_end(int);
void traverse();
void delete_from_begin();
void delete_from_end();
int count = 0;

int main () {
int input, data;

for (;;) {
printf("1. Insert an element at beginning of linked list.\n");
printf("2. Insert an element at end of linked list.\n");
printf("3. Traverse linked list.\n");
printf("4. Delete element from beginning.\n");
printf("5. Delete element from end.\n");
printf("6. Exit\n");
scanf("%d", &input);
if (input == 1) {
printf("Enter value of element\n");
scanf("%d", &data);
insert_at_begin(data);
}
else if (input == 2) {
printf("Enter value of element\n");
scanf("%d", &data);
insert_at_end(data);
}
else if (input == 3)
traverse();
else if (input == 4)
delete_from_begin();
else if (input == 5)
delete_from_end();
else if (input == 6)
break;
else
printf("Please enter valid input.\n");
}
return 0;
}

void insert_at_begin(int x) {
struct node *t;
t = (struct node*)malloc(sizeof(struct node));
count++;
if (start == NULL) {
start = t;
start->data = x;
start->next = NULL;
return;
}
t->data = x;
t->next = start;
start = t;
}
void insert_at_end(int x) {
struct node *t, *temp;
t = (struct node*)malloc(sizeof(struct node));
count++;
if (start == NULL) {
start = t;
start->data = x;
start->next = NULL;
return;
}
temp = start;
while (temp->next != NULL)
temp = temp->next;
temp->next = t;
t->data = x;
t->next = NULL;
}

void traverse() {
struct node *t;
t = start;
if (t == NULL) {
printf("Linked list is empty.\n");
return;
}
printf("There are %d elements in linked list.\n", count);
while (t->next != NULL) {
printf("%d\n", t->data);
t = t->next;
}
printf("%d\n", t->data);
}
void delete_from_begin() {
struct node *t;
int n;
if (start == NULL) {
printf("Linked list is already empty.\n");
return;
}
n = start->data;
t = start->next;
free(start);
start = t;
count--;
printf("%d deleted from beginning successfully.\n", n);
}
void delete_from_end() {
struct node *t, *u;
int n;
if (start == NULL) {
printf("Linked list is already empty.\n");
return;
}
count--;
if (start->next == NULL) {
n = start->data;
free(start);
start = NULL;
printf("%d deleted from end successfully.\n", n);
return;
}
t = start;
while (t->next != NULL) {
u = t;
t = t->next;
}
n = t->data;
u->next = NULL;
free(t);
printf("%d deleted from end successfully.\n", n);
}

Output

Result

Thus, the ‘C’ program to implement linked list using pointers has been executed and the output is
verified successfully.
Ex NO: 5

DATE : LINKED LIST IMPLEMENTATION OF STACK ADT

Aim:
To write a ‘C’ program to implement the linked list using stack ADT.

Algorithm

Step1: Define a array which stores stack elements..


Step 2: The operations on the stack are
a. PUSH data into the stack
b. POP data out of stack
Step 3: PUSH DATA INTO STACK
a.Enter the data to be inserted into stack.
b.If TOP is NULL then the input data is the first node in stack.The link of the node is
NULL.TOP points to that node.
c.If TOP is NOT NULL then the link of TOP points to the new node. TOP points to that node.
step 4: POP DATA FROM STACK
a.If TOP is NULL then the stack is empty
b.If TOP is NOT NULL then the link of TOP is the current TOP.The pervious TOP is popped
from stack.
Step 5: The stack represented by linked list is traversed to display its content.

Program

#include <stdio.h>
#include <stdlib.h>
struct node
{
int info;
struct node *ptr;
}*top,*top1,*temp;
int topelement();
void push(int data);
void pop();
void empty();
void display();
void destroy();
void stack_count();
void create();
int count = 0;
void main()
{
int no, ch, e;
printf("\n 1 - Push");
printf("\n 2 - Pop");
printf("\n 3 - Top");
printf("\n 4 - Empty");
printf("\n 5 - Exit");
printf("\n 6 - Dipslay");
printf("\n 7 - Stack Count");
printf("\n 8 - Destroy stack");
create();
while (1)
{
printf("\n Enter choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("Enter data : ");
scanf("%d", &no);
push(no);
break;
case 2:
pop();
break;
case 3:
if (top == NULL)
printf("No elements in stack");
else
{
e = topelement();
printf("\n Top element : %d", e);
}
break;
case 4:
empty();
break;
case 5:
exit(0);
case 6:
display();
break;
case 7:
stack_count();
break;
case 8:
destroy();
break;
default :
printf(" Wrong choice, Please enter correct choice ");
break;
}
}
}

/* Create empty stack */


void create()
{
top = NULL;
}
/* Count stack elements */
void stack_count()
{
printf("\n No. of elements in stack : %d", count);
}
/* Push data into stack */
void push(int data)
{
if (top == NULL)
{
top =(struct node *)malloc(1*sizeof(struct node));
top->ptr = NULL;
top->info = data;
}
else
{
temp =(struct node *)malloc(1*sizeof(struct node));
temp->ptr = top;
temp->info = data;
top = temp;
}
count++;
}
/* Display stack elements */
void display()
{
top1 = top;
if (top1 == NULL)
{
printf("Stack is empty");
return;
}
while (top1 != NULL)
{
printf("%d ", top1->info);
top1 = top1->ptr;
}
}

/* Pop Operation on stack */


void pop()
{
top1 = top;
if (top1 == NULL)
{
printf("\n Error : Trying to pop from empty stack");
return;
}
else
top1 = top1->ptr;
printf("\n Popped value : %d", top->info);
free(top);
top = top1;
count--;
}
/* Return top element */
int topelement()
{
return(top->info);
}

/* Check if stack is empty or not */


void empty()
{
if (top == NULL)
printf("\n Stack is empty");
else
printf("\n Stack is not empty with %d elements", count);
}
/* Destroy entire stack */
void destroy()
{
top1 = top;
while (top1 != NULL)
{
top1 = top->ptr;
free(top);
top = top1;
top1 = top1->ptr;
}
free(top1);
top = NULL;
printf("\n All stack elements destroyed");
count = 0;
}

Output

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

STACK OPERATIONS USING ARRAY


--------------------------------
1.PUSH
2.POP
3.DISPLAY
4.EXIT

Enter the Choice:1


Enter a value to be pushed:12

Enter the Choice:1


Enter a value to be pushed:24

Result

Thus the C program to implement the linked list using stack ADT has been executed and the
output is verified successfully.
Ex NO: 6
LINKED LIST IMPLEMENTATION OF QUEUE ADT
DATE :

Aim
To write a ‘C ‘program to implement linked list using Queue ADT.

Algorithm
Step1: Define a C-struct for each node in the queue. Each node in the queuecontains data and link to
the next node. Front and rear pointer points to first and last node inserted in the queue.
Step 2: The operations on the queue are
a. INSERT data into the queue
b. DELETE data out of queue
Step 3: INSERT DATA INTO queue
a.Enter the data to be inserted into queue.
b.If TOP is NULL then the input data is the first node in queue.The link of the node is NULL.
TOP points to that node.
c.If TOP is NOT NULL then the link of TOP points to the new node.TOP points to that node.
Step 4: DELETE DATA FROM queue
a.If TOP is NULL then the queue is empty
b.If TOP is NOT NULL then the link of TOP is the current TOP.pervious TOP is popped from
queue.
Step 5: The queue represented by linked list is traversed to display its content.

Program

include <stdio.h>
#include <stdlib.h>
struct node
{
int info;
struct node *ptr;
}*front,*rear,*temp,*front1;

int frontelement();
void enq(int data);
void deq();
void empty();
void display();
void create();
void queuesize();
int count = 0;
void main()
{
int no, ch, e;
printf("\n 1 - Enque");
printf("\n 2 - Deque");
printf("\n 3 - Front element");
printf("\n 4 - Empty");
printf("\n 5 - Exit");
printf("\n 6 - Display");
printf("\n 7 - Queue size");
create();
while (1)
{
printf("\n Enter choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("Enter data : ");
scanf("%d", &no);
enq(no);
break;
case 2:
deq();
break;
case 3:
e = frontelement();
if (e != 0)
printf("Front element : %d", e);
else
printf("\n No front element in Queue as queue is empty");
break;
case 4:
empty();
break;
case 5:
exit(0);
case 6:
display();
break;
case 7:
queuesize();
break;
default:
printf("Wrong choice, Please enter correct choice ");
break;
}
}
}
/* Create an empty queue */
void create()
{
front = rear = NULL;
}
/* Returns queue size */
void queuesize()
{
printf("\n Queue size : %d", count);
}
/* Enqueing the queue */
void enq(int data)
{
if (rear == NULL)
{
rear = (struct node *)malloc(1*sizeof(struct node));
rear->ptr = NULL;
rear->info = data;
front = rear;
}
else
{
temp=(struct node *)malloc(1*sizeof(struct node));
rear->ptr = temp;
temp->info = data;
temp->ptr = NULL;
rear = temp;
}
count++;
}
/* Displaying the queue elements */
void display()
{
front1 = front;
if ((front1 == NULL) && (rear == NULL))
{
printf("Queue is empty");
return;
}
while (front1 != rear)
{
printf("%d ", front1->info);
front1 = front1->ptr;
}
if (front1 == rear)
printf("%d", front1->info);
}
/* Dequeing the queue */
void deq()
{
front1 = front;
if (front1 == NULL)
{
printf("\n Error: Trying to display elements from empty queue");
return;
}
else
if (front1->ptr != NULL)
{
front1 = front1->ptr;
printf("\n Dequed value : %d", front->info);
free(front);
front = front1;
}
else
{
printf("\n Dequed value : %d", front->info);
free(front);
front = NULL;
rear = NULL;
}
count--;
}
/* Returns the front element of queue */
int frontelement()
{
if ((front != NULL) && (rear != NULL))
return(front->info);
else
return 0;
}
/* Display if queue is empty or not */
void empty()
{
if ((front == NULL) && (rear == NULL))
printf("\n Queue empty");
else
printf("Queue not empty");
}

Output
Queue using Array

1.Insertion
2.Deletion
3.Display
4.Exit

Enter the Choice:1


Enter no 1:10
Enter the Choice:1
Enter no 2:54
Enter the Choice:3
Queue Elements are:

10
54

Result

Thus the ‘C’program to implement the Queue using linked list has been executed and the output is
verified successfully.
Ex NO: 7.a
APPLICATION OF STACK-CONVERSION FROM
DATE : INFIX TO POSTFIX EXPRESSION

Aim
To write a C program to convert Infix to Postfix Expression.

Algorithm
1. Start the program
2. Using the strlen function determine the length of the string
3. Declare three arrays; the decremented value of one array is assigned to the incremented value.
This process is repeated until the parenthesis matches.
4. Until t==0 assign the values to sack1
5. Check if (top2==-1) if the condition is satisfied then assign stack2 [++top2]=str[i];
6. Print the result.
7. Stop the program
Program
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
#define SIZE 100
char stack[SIZE];
int top = -1;
void push(char item)
{
if(top >= SIZE-1)
{
printf("\nStack Overflow.");
}
else
{
top = top+1;
stack[top] = item;
}
}
char pop()
{
char item ;
if(top <0)
{
printf("stack under flow: invalid infix expression");
getchar();
exit(1);
}
else
{
item = stack[top];
top = top-1;
return(item);
}
}
int is_operator(char symbol)
{
if(symbol == '^' || symbol == '*' || symbol == '/' || symbol == '+' || symbol =='-')
{
return 1; }
else { return 0; }
}
int precedence(char symbol)
{
if(symbol == '^') /* exponent operator, highest precedence*/
{
return(3);
}
else if(symbol == '*' || symbol == '/')
{
return(2);
}
else if(symbol == '+' || symbol == '-') /* lowest precedence */
{
return(1);
}
else
{
return(0);
}
}
void InfixToPostfix(char infix_exp[], char postfix_exp[])
{
int i, j;
char item;
char x;
push('('); /* push '(' onto stack */
strcat(infix_exp,")"); /* add ')' to infix expression */
i=0;
j=0;
item=infix_exp[i]; /* initialize before loop*/
while(item != '\0') /* run loop till end of infix expression */
{
if(item == '(')
{
push(item);
}
else if( isdigit(item) || isalpha(item)) {
postfix_exp[j] = item;
j++; }

else if(is_operator(item) == 1) /* means symbol is operator */


{
x=pop();
while(is_operator(x) == 1 && precedence(x)>= precedence(item))
{
postfix_exp[j] = x;
/* so pop all higher precendence operator and */
j++;
x = pop() /* add them to postfix expresion */
}
push(x);
/* because just above while loop will terminate we have oppped one extra item for which condition fails
and loop terminates, so that one*/
push(item); /* push current oprerator symbol onto stack */
}
else if(item == ')') /* if current symbol is ')' then */
{
x = pop(); /* pop and keep popping until */
while(x != '(') /* '(' encounterd */
{
postfix_exp[j] = x;
j++;
x = pop();
}
}
else
{
/* if current symbol is neither operand not '(' nor ')' and nor operator */
printf("\nInvalid infix Expression.\n");
/* the it is illegeal symbol */
getchar();
exit(1);
}
i++;
item = infix_exp[i]; /* go to next symbol of infix expression */
}
if(top>0)
{
printf("\nInvalid infix Expression.\n"); /* the it is illegeal symbol */
getchar();
exit(1);
}

postfix_exp[j] = '\0'; /* add sentinel else puts() fucntion */


/* will print entire postfix[] array upto SIZE */
}
int main()
{
char infix[SIZE], postfix[SIZE];
/* declare infix string and postfix string */
printf("ASSUMPTION: The infix expression contains single letter variables and single digit
constants only.\n");
printf("\nEnter Infix expression : ");
gets(infix);
InfixToPostfix(infix,postfix); /* call to convert */
printf("Postfix Expression: ");
puts(postfix); /* print postfix expression */
return 0;}

Output

First Run:

Enter Infix expression : A+(B*C-(D/E^F)*G)*H


Postfix Expression: ABC*DEF^/G*-H*+

Second Run:

Enter Infix expression : (3^2*5)/(3*2-3)+5


Postfix Expression: 32^5*32*3-/5+

Result

Thus the ‘C’ program to convert Infix to Postfix Expression has been executed and the output is
verified successfully.
Ex NO: 7.b
APPLICATIONS OF QUEUE
DATE : FCFS SCHEDULING ALGORITHM

Aim

To write a C program to implement the FCFS scheduling algorithm

Algorithm

Step1:Start the process

Step 2: Declare the array size

Step 3: Get the number of processes to be inserted

Step 4: Get the value

Step 5: Start with the first process from it’s initial position let other process to be in queue

Step 6: Calculate the total number of burst time

Step 7: Display the values

Step 8: Stop the process

Program

#include<stdio.h>
main()
{
int n,a[10],b[10],t[10],w[10],g[10],i,m;
float att=0,awt=0;
for(i=0;i<10;i++)
{
a[i]=0; b[i]=0; w[i]=0; g[i]=0;
}
printf("enter the number of process");
scanf("%d",&n);
printf("enter the burst times");
for(i=0;i<n;i++)
scanf("%d",&b[i]);
printf("\nenter the arrival times");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
g[0]=0;
for(i=0;i<10;i++)
g[i+1]=g[i]+b[i];
for(i=0;i<n;i++)
{
w[i]=g[i]-a[i];
t[i]=g[i+1]-a[i];
awt=awt+w[i];
att=att+t[i];
}
awt =awt/n;
att=att/n;
printf("\n\tprocess\twaiting time\tturn arround time\n");
for(i=0;i<n;i++)
{
printf("\tp%d\t\t%d\t\t%d\n",i,w[i],t[i]);
}
printf("the average waiting time is %f\n",awt);
printf("the average turn around time is %f\n",att);
}

Output
Enter the number of process 4
Enter the burst times
4 9 8 3
Enter the arrival times
0 2 4 3
process waiting time turn around time
p0 0 4
p1 2 11
p2 9 17
p3 18 21
the average waiting time is 7.250000
the average turn around time is 13.250000

Result

Thus the ‘C’ program to implement theFCFS scheduling algorithm has been executed and the output is
verified successfully.
Ex NO: 8
IMPLEMENTATION OF BINARY SEARCH TREES
DATE :
AND TRAVERSALS

Aim

To write a ‘C’ program to implement Binary Search Tree .

Algorithm

Step 1: Start
Step 2: Create a Binary Search Tree for N elements.
Step 3: Traverse the tree in inorder.
Step 4: Traverse the tree in preorder
Step 6: Traverse the tree in postorder.
Step 7: Search the given key element in the BST.
Step 8: Delete an element from BST.
Step 9: Stop

Program

#include <stdlib.h>
typedef struct tnode
{
int data;
struct tnode *right,*left;
}TNODE;

TNODE *CreateBST(TNODE *, int);


void Inorder(TNODE *);
void Preorder(TNODE *);
void Postorder(TNODE *);
main()
{
TNODE *root=NULL; /* Main Program */
int opn,elem,n,i;
do
{
clrscr();
printf("\n ### Binary Search Tree Operations ### \n\n");
printf("\n Press 1-Creation of BST");
printf("\n 2-Traverse in Inorder");
printf("\n 3-Traverse in Preorder");
printf("\n 4-Traverse in Postorder");
printf("\n 5-Exit\n");
printf("\n Your option ? ");
scanf("%d",&opn);
switch(opn)
{
case 1: root=NULL;
printf("\n\nBST for How Many Nodes ?");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("\nRead the Data for Node %d ?",i);
scanf("%d",&elem);
root=CreateBST(root,elem);
}
printf("\nBST with %d nodes is ready to Use!!\n",n);
break;
case 2: printf("\n BST Traversal in INORDER \n");
Inorder(root); break;
case 3: printf("\n BST Traversal in PREORDER \n");
Preorder(root); break;
case 4: printf("\n BST Traversal in POSTORDER \n");
Postorder(root); break;
case 5: printf("\n\n Terminating \n\n"); break;
default: printf("\n\nInvalid Option !!! Try Again !! \n\n");
break;
}
printf("\n\n\n\n Press a Key to Continue . . . ");
getch();
}while(opn != 5);
}
TNODE *CreateBST(TNODE *root, int elem)
{
if(root == NULL)
{
root=(TNODE *)malloc(sizeof(TNODE));
root->left= root->right = NULL;
root->data=elem;
return root;
}
else
{
if( elem < root->data )
root->left=CreateBST(root->left,elem);
else
if( elem > root->data )
root->right=CreateBST(root->right,elem);
else
printf(" Duplicate Element !! Not Allowed !!!");
return(root);
}
}
void Inorder(TNODE *root)
{
if( root != NULL)
{
Inorder(root->left);
printf(" %d ",root->data);
Inorder(root->right); } }

void Preorder(TNODE *root)


{
if( root != NULL)
{
printf(" %d ",root->data);
Preorder(root->left);
Preorder(root->right);
}
}
void Postorder(TNODE *root)
{
if( root != NULL)
{
Postorder(root->left);
Postorder(root->right);
printf(" %d ",root->data);
}
Output

OPERATIONS ---
1 - Insert an element into tree
2 - Delete an element from the tree
3 - Inorder Traversal
4 - Preorder Traversal
5 - Postorder Traversal
6 - Exit

Enter your choice : 1


Enter data of node to be inserted : 40

Enter your choice : 1


Enter data of node to be inserted : 20

Enter your choice : 1


Enter data of node to be inserted : 10

Enter your choice : 1


Enter data of node to be inserted : 30

Enter your choice : 1


Enter data of node to be inserted : 60

Enter your choice : 3


10 -> 20 -> 30 -> 40 -> 60 -> 80 -> 90 ->

Result

Thus, the ‘C’ program to implement Binary search Tree has been executed and the output is verified
successfully.
Ex NO: 9

DATE : IMPLEMENTATION OF AVL TREES

Aim

To write a ‘C’ program to implement AVL Trees

Algorithm

Step 1: Perform the normal BST insertion.


Step 2:The current node must be one of the ancestors of the newly inserted node. Update the height of
the current node.
Step 3:Get the balance factor (left subtree height – right subtree height) of the current node.
Step 4:If balance factor is greater than 1, then the current node is unbalanced and we are either in Left
Left case or left Right case. To check whether it is left left case or not, compare the newly
inserted key with the key in left subtree root.
Step 5:If balance factor is less than -1, then the current node is unbalanced and we are either in Right
Right case or Right-Left case. To check whether it is Right Right case or not, compare the newly
inserted key with the key in right subtree root.

Program

#include<stdio.h>
typedef struct node
{
int data;
struct node *left,*right;
int ht;
}node;

node *insert(node *,int);


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

int main()
{
node *root=NULL;
int x,n,i,op;
clrscr();
do
{
printf("\n1)Create:");
printf("\n2)Insert:");
printf("\n3)Delete:");
printf("\n4)Print:");
printf("\n5)Quit:");
printf("\n\nEnter Your Choice:");
scanf("%d",&op);
switch(op)
{
case 1: printf("\nEnter no. of elements:");
scanf("%d",&n);
printf("\nEnter tree data:");
root=NULL;
for(i=0;i<n;i++)
{
scanf("%d",&x);
root=insert(root,x);
}
break;
case 2: printf("\nEnter a data:");
scanf("%d",&x);
root=insert(root,x);
break;

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


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

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


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

node * insert(node *T,int x)


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

T->ht=height(T);
return(T);
}

node * Delete(node *T,int x)


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

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

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

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


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

int height(node *T)


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

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

if(T->right==NULL)
rh=0;
else
rh=1+T->right->ht;
if(lh>rh)
return(lh);
return(rh);
}
node * rotateright(node *x)
{
node *y;
y=x->left;
x->left=y->right;
y->right=x;
x->ht=height(x);
y->ht=height(y);
return(y);
}

node * rotateleft(node *x)


{
node *y;
y=x->right;
x->right=y->left;
y->left=x;
x->ht=height(x);
y->ht=height(y);
return(y);
}
node * RR(node *T)
{
T=rotateleft(T);
return(T);
}
node * LL(node *T)
{
T=rotateright(T);
return(T);
}
node * LR(node *T)
{
T->left=rotateleft(T->left);
T=rotateright(T);
return(T);
}
node * RL(node *T)
{
T->right=rotateright(T->right);
T=rotateleft(T);
return(T);
}
int BF(node *T)
{
int lh,rh;
if(T==NULL)
return(0);
if(T->left==NULL)
lh=0;
else
lh=1+T->left->ht;

if(T->right==NULL)
rh=0;
else
rh=1+T->right->ht;
return(lh-rh);
}
void preorder(node *T)
{
if(T!=NULL)
{
printf("%d(Bf=%d)",T->data,BF(T));
preorder(T->left);
preorder(T->right);
}
}
void inorder(node *T)
{
if(T!=NULL)
{
inorder(T->left);
printf("%d(Bf=%d)",T->data,BF(T));
inorder(T->right);
}
}

Output

Preorder traversal of the constructed AVL tree is


30 20 10 25 40 50

Result

Thus the ‘C’ program to implement the AVL Tree has been executed and the output is verified
successfully.
Ex NO: 10 IMPLEMENTATION OF HEAPS USING
DATE : PRIORITY QUEUES

Aim

To write a ‘C’ program to implement Priority Queues using heap.

Algorithm

Step 1: Start
Step 2: Initialize all necessary variables and functions.
Step 3: Read the choices.
Step 4: For insertion, read the element to be inserted.
Step 5: If root is NULL, assign the given element as root.
Step 6: If the element is equal to the root, print “Duplicate value”.
Step 7: Else if element value is less than the root value, insert element at the left of the root.
Step 8: Else insert right side of the root.For deletion, get the priority for maximum or minimum.
Step 9: If maximum, it deletes the root and rearranges the tree.
Step 10: If minimum, it deletes the leaf.
Step 11:End of the program

Program

#include<stdio.h>
struct heapstruct
{
int capacity;
int size;
int *a;
};
typedef struct heapstruct *pq;
pq initialize(int maxa,int mindata)
{
pq h;
h=(struct heapstruct*)malloc(sizeof(struct heapstruct));
if(h==NULL)
printf(“\nOut of Space”);
h->a=(int*)malloc((maxa+1)*sizeof(int));
h->capacity=maxa;
h->size=0;
h->a[0]=mindata;
return h;
}
void insert(int x,pq h)
{
int i;
if(h->size==h->capacity)
{
printf(“\nFull”);
}
else
{
for(i=++h->size;h->a[i/2]>x;i=i/2)
{
h->a[i]=h->a[i/2];
}
h->a[i]=x;
}
}
int delmin(pq h)
{
int i,mina,lasta,child;
if(h->size==0)
{
return(h->a[0]);
}
else
{
mina=h->a[1];
lasta=h->a[h->size--];
for(i=1;i*2size;i=child)
{
child=i*2;
if(child!=h->size && h->a[child+1]a[child])
child++;
if(lasta>h->a[child])
{
h->a[i]=h->a[child];
}
else
break;
}
h->a[i]=lasta;
return mina;
}
}
void display(pq h)
{
int i;
for(i=1;isize;i++)
{
printf(“\nThe data is: %d”,h->a[i]);
}
}
void main()
{
pq h;int x,y,z,u,v;char ch;
clrscr();
printf(“\nEnter the maximum number of elements for the Priority Queue:”);
scanf(“%d”,&x);
printf(“\nEnter the minimum element :”);
scanf(“%d”,&y);
h=initialize(x,y);
menu:
printf(“\nPriority Queue”);
printf(“\n1.Insert\n2.Delete\n3.Display\n4.Exit”);
scanf(“%d”,&u);
switch(u)
{
case 1:printf(“Enter the Data:”);
scanf(“%d”,&z);
insert(z,h);
break;
case 2:v=delmin(h);
printf(“\nThe deleted element is: %d”,v);
break;
case 3:display(h);
break;
case 4:exit(0);
}
goto menu;
}
Output

.....MAIN MENU.....
1.Insert.
2.Delete.
3.Display.
4.Quit.
Enter your choice : 1
Enter data to be inserted : 5
.....MAIN MENU.....
1.Insert.
2.Delete.
3.Display.
4.Quit.
Enter your choice : 1
Enter data to be inserted : 3
.....MAIN MENU.....
1.Insert.
2.Delete.
3.Display.
4.Quit.
Enter your choice : 1
Enter data to be inserted : 2
.....MAIN MENU.....
1.Insert.
2.Delete.
3.Display.
4.Quit.
Enter your choice : 3

532

Result

Thus, the ‘C’ program to implement Heaps using priority Queues been executed and the output is
verified successfully.
Ex NO: 11 IMPLEMENTATION OF GRAPH AND
DATE : TRAVERSAL ALGORITHMS

Aim

To write a ‘C’ program to implement Depth First Search (DFS) using Adjacency Matrix
representation of graph.

Algorithm

The DFS algorithm works as follows:

Step 1: Start by putting any one of the graph's vertices on top of a stack.

Step 2: Take the top item of the stack and add it to the visited list.

Step 3: Create a list of that vertex's adjacent nodes. Add the ones, which are not in the visited list to the

top of stack.

Step 4: Keep repeating steps 2 and 3 until the stack is empty.

Program

#include<stdio.h>
void DFS(int);
int G[10][10],visited[10],n; //n is no of vertices and graph is sorted in array G[10][10]
void main()
{
int i,j;
printf("Enter number of vertices:");
scanf("%d",&n);
//read the adjecency matrix
printf("\nEnter adjecency matrix of the graph:");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
//visited is initialized to zero
for(i=0;i<n;i++)
visited[i]=0;
DFS(0);
}
void DFS(int i)
{
int j;
printf("\n%d",i);
visited[i]=1;
for(j=0;j<n;j++)
if(!visited[j]&&G[i][j]==1)
DFS(j);}

Output:

Result

Thus, the ‘C’program to implement Depth First Search (DFS) has been executed and the output is
verified successfully.
Ex NO: 12.a
IMPLEMENTATION OF BUBBLE SORT
DATE :

Aim

To write a ‘C’ program to implement bubble sort technique.

Algorithm

Step 1: Initialize the variables i,j,n, and temp.

Step 2: Get the number of elements.

Step 3: Get the numbers to be sorted.

Step 4; Assign a[i] to temp

Step 5: Assign a[i+1] to a[i]

Step 6: Assign Temp to a[i+1]

Step 7: The data is sorted

Program

#include <stdio.h>
void bubblesort(int arr[], int size)
{
int i, j;
for (i = 0; i < size; i++)
{
for (j = 0; j < size - i; j++)
{
if (arr[j] > arr[j+1])
swap(&arr[j], &arr[j+1]);
}
}
}
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}

int main()
{
int array[100], i, size;
printf("How many numbers you want to sort: ");
scanf("%d", &size);
printf("\nEnter %d numbers : ", size);
for (i = 0; i < size; i++)
scanf("%d", &array[i]);
bubblesort(array, size);
printf("\nSorted array is ");
for (i = 0; i < size; i++)
printf(" %d ", array[i]);
return 0;
}

Output

Result

Thus the ‘C’ program to implement bubble sort has been executed and the output is verified
successfully.
Ex NO: 12.b
IMPLEMENTATION OF QUICK SORT
DATE :

Aim

To write a ‘C’ program to implement Quick sort.

Algorithm

Step 1: Choose the highest index value has pivot


Step 2: Take two variables to point left and right of the list excluding pivot
Step 3: left points to the low index
Step 4: right points to the high
Step 5: while value at left is less than pivot move right
Step 6: while value at right is greater than pivot move left
Step 7: If both step 5 and step 6 does not match swap left and right
Step 8: If left ≥ right, the point where they met is new pivot

Program

#include<stdio.h>
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)
{
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: 5 22 -19 63 1
The Sorted Order is: -19 1 5 22 63

Result

Thus the ‘C’ program to implement Quick sort has been executed and the output is verified successfully.
Ex NO: 13.a
IMPLEMENTATION OF LINEAR SEARCH
DATE :

Aim

To write a ‘C’ program to implement Linear search.

Algorithm

Step 1: Initialize the integer variables

Step 2: Get the number of elements and its values

Step 3: Start from the leftmost element of arr[] and one by one compare x with each element of arr[]

Step 4: If x matches with an element, return the index.

Step 5: If x doesn’t match with any of elements, return -1.

Step 6: Stop the program

Program

#include<stdio.h>
int main()
{
int a[20],i,x,n;
printf("How many elements?:");
scanf("%d",&n);

printf("Enter array elements:n");


for(i=0;i<n;++i)
scanf("%d",&a[i]);

printf("nEnter element to search:");


scanf("%d",&x);

for(i=0;i<n;++i)
if(a[i]==x)
break;
if(i<n)
printf("Element found at index %d",i);
else
printf("Element not found");

return 0;
}

Output:

Result

Thus the ‘C’ program to implement the Linear search has been executed and the output is
verified successfully.
Ex NO: 13.b
IMPLEMENTATION OF BINARY SEARCH
DATE :

Aim

To write a ‘C’ program to implement binary search.

Algorithm

Step 1: Initialize the integer variables

Step 2: Get the values from the list

Step 3: Sorted List of numbers is got as input.

Step 4: Get the target number from the user.

Step 5: Initialize first value as zero and last as n-1;

Step 6: The mid value is found.

Step 7: If the target is greater than mid then first is mid + 1 if not last is mid -1

Step 8: First is last +1

Step 9: The target is found, if its equal to a(mid) otherwise target is not found.

Program

#include <stdio.h>
int main()
{
int c, first, last, middle, n, search, array[100];
printf("Enter number of elements\n");
scanf("%d",&n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d",&array[c]);

printf("Enter value to find\n");


scanf("%d", &search);
first = 0;
last = n - 1;
middle = (first+last)/2;
while (first <= last) {
if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search) {
printf("%d found at location %d.\n", search, middle+1);
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
printf("Not found! %d isn't present in the list.\n", search);
return 0;
}

Output:

Result

Thus the ‘C’ program to implement the binary search has been executed and the output is
verified successfully.
Ex NO: 14
HASHING – ANY TWO COLLISION TECHNIQUES
DATE :

Aim

To write a C program toimplement Hashing using Linear and Quadratic Probing.

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. But, the size ofarraymust be
immediately updated to a prime number just greater than initial array
Step 3: A menu is displayed on the screen.
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

Program

#include <stdio.h>
#include <conio.h>
int tsize;
int hasht(int key)
{
int i ;
i = key%tsize ;
return i;
}
//-------LINEAR PROBING-------
int rehashl(int key)
{
int i ;
i = (key+1)%tsize ;
return i ;
}
//-------QUADRATIC PROBING-------
int rehashq(int key, int j)
{
int i ;
i = (key+(j*j))%tsize ;
return i ; }
void main()
{
int key,arr[20],hash[20],i,n,s,op,j,k ;
clrscr() ;
printf ("Enter the size of the hash table: ");
scanf ("%d",&tsize);
printf ("\nEnter the number of elements: ");
scanf ("%d",&n);
for (i=0;i<tsize;i++)
hash[i]=-1 ;
printf ("Enter Elements: ");
for (i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
do
{
printf("\n\n1.Linear Probing\n2.Quadratic Probing \n3.Exit \nEnter your option: ");
scanf("%d",&op);
switch(op)
{
case 1:
for (i=0;i<tsize;i++)
hash[i]=-1 ;
for(k=0;k<n;k++)
{
key=arr[k] ;
i = hasht(key);
while (hash[i]!=-1)
{
i = rehashl(i);
}
hash[i]=key ;
}
printf("\nThe elements in the array are: ");
for (i=0;i<tsize;i++)
{
printf("\n Element at position %d: %d",i,hash[i]);
}
break ;
case 2:
for (i=0;i<tsize;i++)
hash[i]=-1 ;
for(k=0;k<n;k++)
{
j=1;
key=arr[k] ;
i = hasht(key);
while (hash[i]!=-1)
{
i = rehashq(i,j);
j++ ;
}
hash[i]=key ;
}
printf("\nThe elements in the array are: ");
for (i=0;i<tsize;i++)
{
printf("\n Element at position %d: %d",i,hash[i]);
}
break ;
}
}while(op!=3);
getch() ; }

Output
Enter the size of the hash table: 10

Enter the number of elements: 8


Enter Elements: 72 27 36 24 63 81 92 101

1.Linear Probing
2.Quadratic Probing
3.Exit
Enter your option: 1

The elements in the array are:


Element at position 0: -1
Element at position 1: 81
Element at position 2: 72
Element at position 3: 63
Element at position 4: 24
Element at position 5: 92
Element at position 6: 36
Element at position 7: 27
Element at position 8: 101
Element at position 9: -1

1.Linear Probing
2.Quadratic Probing
3.Exit
Enter your option: 2

Result

Thus the ‘C’ program to implement Hashing using Linear and Quadratic Probing has been executed and the
output is verified successfully.

Ex NO: 15 CONTENT BEYOND SYLLABUS


DATE : APPLICATIONS OF GRAPHS – DIJIKSTRA’S
ALGORITHM
Aim

To write a ‘C’ program to implement Dijikstra’s Algorithms.

Algorithm

Step 1 : Begin

Step 2: Create cost matrix C[ ][ ] from adjacency matrix adj[ ][ ]. C[i][j] is the cost of going from vertex
i to vertex j. If there is no edge between vertices i and j then C[i][j] is infinity.

Step 3: Array visited[ ] is initialized to zero.


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

Step 4: If the vertex 0 is the source vertex then visited[0] is marked as 1.

Step 5: Create the distance matrix, by storing the cost of vertices from vertex no. 0 to n-1 from the
source vertex 0.
for(i=1;i<n;i++)
distance[i]=cost[0][i];
Initially, distance of source vertex is taken as 0. i.e. distance[0]=0;

Step 6: for(i=1;i<n;i++)
– Choose a vertex w, such that distance[w] is minimum and visited[w] is 0. Mark visited[w] as 1.
Recalculate the shortest distance of remaining vertices from the source.
– Only, the vertices not marked as 1 in array visited[ ] should be considered for recalculation of
distance. i.e. for each vertex v
if(visited[v]==0)
distance[v]=min(distance[v],
distance[w]+cost[w][v])

Step 7: Return

Program

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

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


int main()
{
int G[MAX][MAX],i,j,n,u;
printf("Enter no. of vertices:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");

for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);

printf("\nEnter the starting node:");


scanf("%d",&u);
dijkstra(G,n,u);

return 0;
}
void dijkstra(int G[MAX][MAX],int n,int startnode)
{
int cost[MAX][MAX],distance[MAX],pred[MAX];
int visited[MAX],count,mindistance,nextnode,i,j;

//pred[] stores the predecessor of each node


//count gives the number of nodes seen so far
//create the cost matrix
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(G[i][j]==0)
cost[i][j]=INFINITY;
else
cost[i][j]=G[i][j];

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


for(i=0;i<n;i++)
{
distance[i]=cost[startnode][i];
pred[i]=startnode;
visited[i]=0;
}
distance[startnode]=0;
visited[startnode]=1;
count=1;
while(count<n-1)
{
mindistance=INFINITY;
//nextnode gives the node at minimum distance
for(i=0;i<n;i++)
if(distance[i]<mindistance&&!visited[i])
{
mindistance=distance[i];
nextnode=i;
}
//check if a better path exists through nextnode
visited[nextnode]=1;
for(i=0;i<n;i++)
if(!visited[i])
if(mindistance+cost[nextnode][i]<distance[i])
{
distance[i]=mindistance+cost[nextnode][i];
pred[i]=nextnode;
}
count++;
}
//print the path and distance of each node
for(i=0;i<n;i++)
if(i!=startnode)
{
printf("\nDistance of node%d=%d",i,distance[i]);
printf("\nPath=%d",i);

j=i;
do
{
j=pred[j];
printf("<-%d",j);
}while(j!=startnode);
}
}

Output
Enter the no. of vertices :5

Enter the adjacency matris

0 10 0 30 100
10 0 50 0 0
0 50 0 20 10
30 0 20 0 60
100 0 10 60 0

Enter the starting node :0

Distance of node 1=10


Path :1<-0

Distance of node 2=50


Path :2<-3<-0

Distance of node 3=30


Path :3<-0

Distance of node 4=60


Path : 4<-2<-3<-0

Process returned 5 (0x5)


Execution time : 47.471 s

Press any key to continue

Result

Thus, the ‘C’program to implement Dijikstra’s Algorithm has been executed and the output is verified
successfully.

Ex NO: 16 CONTENT BEYOND SYLLABUS


DATE : IMPLEMENTATION OF RADIX SORT
Aim

To write a ‘C’ program to implement Radix sort.

Algorithm

Step 1:Start the program

Step 2: In 1st pass,we sort the array on basis of least significant digit (1s place) using counting sort.

Step 3: In 2nd pass,we sort the array on basis of next digit (10s place) using counting sort.

Step 4: In 3rd pass,we sort the array on basis of most significant digit (100s place) using counting sort.

Step 5: Stop the Program

Program

#include<stdio.h>
#include<conio.h>
radix_sort(int array[], int n);
void main()
{
int array[100],n,i;
clrscr();
printf("\t\t\tRadix Sort\n\n\n\n");
printf("Enter the number of elements to be sorted: ");
scanf("%d",&n);
printf("\nEnter the elements to be sorted: \n");
for(i = 0 ; i < n ; i++ )
{
printf("\tArray[%d] = ",i);
scanf("%d",&array[i]);
}
printf("\nArray Before Radix Sort:"); //Array Before Radix Sort
for(i = 0; i < n; i++)
{
printf("%8d", array[i]);
}
printf("\n");
radix_sort(array,n);
printf("\nArray After Radix Sort: "); //Array After Radix Sort
for(i = 0; i < n; i++)
{
printf("%8d", array[i]);
}
printf("\n");
getch();
}
radix_sort(int arr[], int n)
{
int bucket[10][5],buck[10],b[10];
int i,j,k,l,num,div,large,passes;
div=1;
num=0;
large=arr[0];
for(i=0 ; i<n ; i++)
{
if(arr[i] > large)
{
large = arr[i];
}
while(large > 0)
{
num++;
large = large/10;
}
for(passes=0 ; passes<num ; passes++)
{
for(k=0 ; k<10 ; k++)
{
buck[k] = 0;
}
for(i=0 ; i<n ;i++)
{
l = ((arr[i]/div)%10);
bucket[l][buck[l]++] = arr[i];
}
i=0;
for(k=0 ; k<10 ; k++)
{
for(j=0 ; j<buck[k] ; j++)
{
arr[i++] = bucket[k][j];
}
}
div*=10;
}
}
return 0;}

Output:
Result

Thus the ‘C’ program to implement the Radix sort using array has been executed and the output is verified
successfully.

You might also like