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

ADS LAB MANUAL(M-TECH)

The document outlines programming assignments for implementing data structures including stacks using linked lists, circular queues using arrays, singly linked lists, and doubly linked lists. Each section includes algorithms and C code for operations such as insertion, deletion, and display of elements. The document serves as a comprehensive guide for students to understand and implement these fundamental data structures.

Uploaded by

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

ADS LAB MANUAL(M-TECH)

The document outlines programming assignments for implementing data structures including stacks using linked lists, circular queues using arrays, singly linked lists, and doubly linked lists. Each section includes algorithms and C code for operations such as insertion, deletion, and display of elements. The document serves as a comprehensive guide for students to understand and implement these fundamental data structures.

Uploaded by

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

WEEK-1

AIM: Program To Implement Stack Using Linked list.

ALGORITHM:

Step-1: Include all the header files which are used in the program. And declare all the user defined
functions.
Step-2: Define a 'Node' structure with two members data and next.
Step-3: Define a Node pointer 'top' and set it to NULL.
Step 4 - Implement the main method by displaying Menu with list of operations and make suitable
function calls in the main method.

For inserting a value into stack


Step a - Create a newNode with given value.
Step b - Check whether stack is Empty (top == NULL)
Step c - If it is Empty, then set newNode → next = NULL.
Step d - If it is Not Empty, then set newNode → next = top.
Step e - Finally, set top = newNode.

For deleting a value from stack

Step 1 - Check whether stack is Empty (top == NULL).


Step 2 - If it is Empty, then display "Stack is Empty!!! Deletion is not possible!!!" and terminate the
function
Step 3 - If it is Not Empty, then define a Node pointer 'temp' and set it to 'top'.
Step 4 - Then set 'top = top → next'.
Step 5 - Finally, delete 'temp'. (free(temp)).

For displaying elements in the stack

Step 1 - Check whether stack is Empty (top == NULL).


Step 2 - If it is Empty, then display 'Stack is Empty!!!' and terminate the function.
Step 3 - If it is Not Empty, then define a Node pointer 'temp' and initialize with top.
Step 4 - Display 'temp → data --->' and move it to the next node. Repeat the same until temp reaches to
the first node in the stack. (temp → next != NULL).
Step 5 - Finally! Display 'temp → data ---> NULL'.

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
WEEK-2

AIM: Write a program to implement circular queue operations using arrays.

ALOGRITHM:

Step 1 - Include all the header files which are used in the program and define a constant 'SIZE' with
specific value.
Step 2 - Declare all user defined functions used in circular queue implementation.
Step 3 - Create a one dimensional array with above defined SIZE (int cQueue[SIZE])
Step 4 - Define two integer variables 'front' and 'rear' and initialize both with '-1'. (int front = -1, rear = -
1)
Step 5 - Implement main method by displaying menu of operations list and make suitable function calls
to perform operation selected by the user on circular queue.

ENQUEUE(INSERT OPERATION)

Step 1 - Check whether queue is FULL. ((rear == SIZE-1 && front == 0) || (front == rear+1))
Step 2 - If it is FULL, then display "Queue is FULL!!! Insertion is not possible!!!" and terminate the
function.
Step 3 - If it is NOT FULL, then check rear == SIZE - 1 && front != 0 if it is TRUE, then set rear = -1.
Step 4 - Increment rear value by one (rear++), set queue[rear] = value and check 'front == -1' if it is TRUE,
then set front = 0.

DEQUEUE(DELETE OPERATION)

Step 1 - Check whether queue is EMPTY. (front == -1 && rear == -1)


Step 2 - If it is EMPTY, then display "Queue is EMPTY!!! Deletion is not possible!!!" and terminate the
function.
Step 3 - If it is NOT EMPTY, then display queue[front] as deleted element and increment the front value
by one (front ++). Then check whether front == SIZE, if it is TRUE, then set front = 0. Then check whether
both front - 1 and rear are equal (front -1 == rear), if it TRUE, then set both front and rear to '-1' (front =
rear = -1).

DISPLAY OPERATION

Step 1 - Check whether queue is EMPTY. (front == -1)


Step 2 - If it is EMPTY, then display "Queue is EMPTY!!!" and terminate the function.
Step 3 - If it is NOT EMPTY, then define an integer variable 'i' and set 'i = front'.
Step 4 - Check whether 'front <= rear', if it is TRUE, then display 'queue[i]' value and increment 'i' value
by one (i++). Repeat the same until 'i <= rear' becomes FALSE.
Step 5 - If 'front <= rear' is FALSE, then display 'queue[i]' value and increment 'i' value by one (i++).
Repeat the same until'i <= SIZE - 1' becomes FALSE.
Step 6 - Set i to 0.
Step 7 - Again display 'cQueue[i]' value and increment i value by one (i++). Repeat the same until 'i <=
rear' becomes FALSE.
PROGRAM

#include<stdio.h>
#define max 3
int q[10],front=0,rear=-1;
void main()
{
int ch;
void insert();
void delet();
void display();
clrscr();
printf("\nCircular Queue operations\n");
printf("1.insert\n2.delete\n3.display\n4.exit\n");
while(1)
{
printf("Enter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1: insert( );
break;
case 2: delet( );
break;
case 3:display( );
break;
case 4:exit( );
default:printf("Invalid option\n");
}
}
}
void insert()
{
int x;
if((front==0&&rear==max-1)||(front>0&&rear==front-1))
printf("Queue is overflow\n");
else
{
printf("Enter element to be insert:");
scanf("%d",&x);
if(rear==max-1&&front>0)
{
rear=0;
q[rear]=x;
}
else
{
if((front==0&&rear==-1)||(rear!=front-1))
q[++rear]=x;
}
}
}
void delet()
{
int a;
if((front==0)&&(rear==-1))
{
printf("Queue is underflow\n");
getch();
exit();
}
if(front==rear)
{
a=q[front];
rear=-1;
front=0;
}
else
if(front==max-1)
{
a=q[front];
front=0;
}
else a=q[front++];
printf("Deleted element is:%d\n",a);
}
void display()
{
int i,j;
if(front==0&&rear==-1)
{
printf("Queue is underflow\n");
getch();
exit();
}
if(front>rear)
{
for(i=0;i<=rear;i++)
printf("\t%d",q[i]);
for(j=front;j<=max-1;j++)
printf("\t%d",q[j]);
printf("\nrear is at %d\n",q[rear]);
printf("\nfront is at %d\n",q[front]);
}
else
{
for(i=front;i<=rear;i++)
{
printf("\t%d",q[i]);
}
printf("\nrear is at %d\n",q[rear]);
printf("\nfront is at %d\n",q[front]);
}
printf("\n");
}
getch();
}

OUTPUT
WEEK-3

AIM: Write a program to implement the following operations on singly linked list
a) Creation of a linked list b) Insert a node into linked list c) Delete a node from linked list

ALGORITHM

INSERT OPERATION

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.

DISPLAY OPERATION

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 num; //Data of the node
struct node *nextptr; //Address of the next node
}*stnode;

void createNodeList(int n); // function to create the list


void displayList(); // function to display the list

int main()
{
int n;
printf("\n\n Linked List : To create and display Singly Linked List :\n");
printf("-------------------------------------------------------------\n");

printf(" Input the number of nodes : ");


scanf("%d", &n);
createNodeList(n);
printf("\n Data entered in the list : \n");
displayList();
return 0;
}
void createNodeList(int n)
{
struct node *fnNode, *tmp;
int num, i;
stnode = (struct node *)malloc(sizeof(struct node));

if(stnode == NULL) //check whether the fnnode is NULL and if so no memory allocation
{
printf(" Memory can not be allocated.");
}
else
{
// reads data for the node through keyboard

printf(" Input data for node 1 : ");


scanf("%d", &num);
stnode->num = num;
stnode->nextptr = NULL; // links the address field to NULL
tmp = stnode;
// Creating n nodes and adding to linked list
for(i=2; i<=n; i++)
{
fnNode = (struct node *)malloc(sizeof(struct node));
if(fnNode == NULL)
{
printf(" Memory can not be allocated.");
break;
}
else
{
printf(" Input data for node %d : ", i);
scanf(" %d", &num);

fnNode->num = num; // links the num field of fnNode with num


fnNode->nextptr = NULL; // links the address field of fnNode with NULL

tmp->nextptr = fnNode; // links previous node i.e. tmp to the fnNode


tmp = tmp->nextptr;
}
}
}
}
void displayList()
{
struct node *tmp;
if(stnode == NULL)
{
printf(" List is empty.");
}
else
{
tmp = stnode;
while(tmp != NULL)
{
printf(" Data = %d\n", tmp->num); // prints the data of current node
tmp = tmp->nextptr; // advances the position of current node
}
}
}

OUTPUT
WEEK-4

AIM: Write a program to implement the following operations on doubly linked list
a) Creation of a linked list b) Insert a node in to linked list c) Delete a node from linked list

ALGORITHM

INSERT OPERATION

Step 1 - Create a newNode with given value and newNode → previous as NULL.
Step 2 - Check whether list is Empty (head == NULL)
Step 3 - If it is Empty then, assign NULL to newNode → next and newNode to head.
Step 4 - If it is not Empty then, assign head to newNode → next and newNode to head.

DELETE OPERATION

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 → previous is equal to temp → next)
Step 5 - If it is TRUE, then set head to NULL and delete temp (Setting Empty list conditions)
Step 6 - If it is FALSE, then assign temp → next to head, NULL to head → previous and delete temp.

DISPLAY OPERATION

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 - Display 'NULL <--- '.
Step 5 - Keep displaying temp → data with an arrow (<===>) until temp reaches to the last node
Step 6 - Finally, display temp → data with arrow pointing to NULL (temp → data ---> NULL).

PROGRAM

#include<stdio.h>
#include<stdlib.h>
struct node
{
struct node *prev;
struct node *next;
int data;
};
struct node *head;
void insertion_beginning();
void insertion_last();
void insertion_specified();
void deletion_beginning();
void deletion_last();
void deletion_specified();
void display();
void search();
void main ()
{
int choice =0;
while(choice != 9)
{
printf("\n*********Main Menu*********\n");
printf("\nChoose one option from the following list ...\n");
printf("\n===============================================\n");
printf("\n1.Insert in begining\n2.Insert at last\n3.Insert at any random location\n4.Delete from
Beginning\n
5.Delete from last\n6.Delete the node after the given data\n7.Search\n8.Show\n9.Exit\n");
printf("\nEnter your choice?\n");
scanf("\n%d",&choice);
switch(choice)
{
case 1:
insertion_beginning();
break;
case 2:
insertion_last();
break;
case 3:
insertion_specified();
break;
case 4:
deletion_beginning();
break;
case 5:
deletion_last();
break;
case 6:
deletion_specified();
break;
case 7:
search();
break;
case 8:
display();
break;
case 9:
exit(0);
break;
default:
printf("Please enter valid choice..");
}
}
}
void insertion_beginning()
{
struct node *ptr;
int item;
ptr = (struct node *)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
{
printf("\nEnter Item value");
scanf("%d",&item);

if(head==NULL)
{
ptr->next = NULL;
ptr->prev=NULL;
ptr->data=item;
head=ptr;
}
else
{
ptr->data=item;
ptr->prev=NULL;
ptr->next = head;
head->prev=ptr;
head=ptr;
}
printf("\nNode inserted\n");
}

}
void insertion_last()
{
struct node *ptr,*temp;
int item;
ptr = (struct node *) malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
{
printf("\nEnter value");
scanf("%d",&item);
ptr->data=item;
if(head == NULL)
{
ptr->next = NULL;
ptr->prev = NULL;
head = ptr;
}
else
{
temp = head;
while(temp->next!=NULL)
{
temp = temp->next;
}
temp->next = ptr;
ptr ->prev=temp;
ptr->next = NULL;
}

}
printf("\nnode inserted\n");
}
void insertion_specified()
{
struct node *ptr,*temp;
int item,loc,i;
ptr = (struct node *)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("\n OVERFLOW");
}
else
{
temp=head;
printf("Enter the location");
scanf("%d",&loc);
for(i=0;i<loc;i++)
{
temp = temp->next;
if(temp == NULL)
{
printf("\n There are less than %d elements", loc);
return;
}
}
printf("Enter value");
scanf("%d",&item);
ptr->data = item;
ptr->next = temp->next;
ptr -> prev = temp;
temp->next = ptr;
temp->next->prev=ptr;
printf("\nnode inserted\n");
}
}
void deletion_beginning()
{
struct node *ptr;
if(head == NULL)
{
printf("\n UNDERFLOW");
}
else if(head->next == NULL)
{
head = NULL;
free(head);
printf("\nnode deleted\n");
}
else
{
ptr = head;
head = head -> next;
head -> prev = NULL;
free(ptr);
printf("\nnode deleted\n");
}

}
void deletion_last()
{
struct node *ptr;
if(head == NULL)
{
printf("\n UNDERFLOW");
}
else if(head->next == NULL)
{
head = NULL;
free(head);
printf("\nnode deleted\n");
}
else
{
ptr = head;
if(ptr->next != NULL)
{
ptr = ptr -> next;
}
ptr -> prev -> next = NULL;
free(ptr);
printf("\nnode deleted\n");
}
}
void deletion_specified()
{
struct node *ptr, *temp;
int val;
printf("\n Enter the data after which the node is to be deleted : ");
scanf("%d", &val);
ptr = head;
while(ptr -> data != val)
ptr = ptr -> next;
if(ptr -> next == NULL)
{
printf("\nCan't delete\n");
}
else if(ptr -> next -> next == NULL)
{
ptr ->next = NULL;
}
else
{
temp = ptr -> next;
ptr -> next = temp -> next;
temp -> next -> prev = ptr;
free(temp);
printf("\nnode deleted\n");
}
}
void display()
{
struct node *ptr;
printf("\n printing values...\n");
ptr = head;
while(ptr != NULL)
{
printf("%d\n",ptr->data);
ptr=ptr->next;
}
}
void search()
{
struct node *ptr;
int item,i=0,flag;
ptr = head;
if(ptr == NULL)
{
printf("\nEmpty List\n");
}
else
{
printf("\nEnter item which you want to search?\n");
scanf("%d",&item);
while (ptr!=NULL)
{
if(ptr->data == item)
{
printf("\nitem found at location %d ",i+1);
flag=0;
break;
}
else
{
flag=1;
}
i++;
ptr = ptr -> next;
}
if(flag==1)
{
printf("\nItem not found\n");
}
}
}

OUTPUT
WEEK-5

AIM: Write a program to implement the following.a)Linear probing b)Quadratic probing c)Double
hashing.

ALGORITHM

LINEAR PROBING
If slot hash(x) % S is full, then we try (hash(x) + 1) % S
If (hash(x) + 1) % S is also full, then we try (hash(x) + 2) % S
If (hash(x) + 2) % S is also full, then we try (hash(x) + 3) % S

QUADRATIC PROBING
If slot hash(x) % S is full, then we try (hash(x) + 1*1) % S
If (hash(x) + 1*1) % S is also full, then we try (hash(x) + 2*2) % S
If (hash(x) + 2*2) % S is also full, then we try (hash(x) + 3*3) % S

DOUBLE HASHING
If slot hash(x) % S is full, then we try (hash(x) + 1*hash2(x)) % S
If (hash(x) + 1*hash2(x)) % S is also full, then we try (hash(x) + 2*hash2(x)) % S
If (hash(x) + 2*hash2(x)) % S is also full, then we try (hash(x) + 3*hash2(x)) % S

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 ;
}
int hashdouble(int key)
{
int j,i,index;
for(i=0;i<tsize;i++)
{
j=7-(key%7);
index=(key+(i*j)%tsize);
}
return index;
}
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.Double hashing 4.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 ;
case 3: 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 = hashdouble(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 ;
}
}while(op!=4);
getch() ;
}
OUTPUT
WEEK-6

AIM: Write a program to implement the following in binary search tree


a) Creation b) Insertion c) Deletion

ALGORITHM
INSERT OPERATION

Step 1 - Create a newNode with given value and set its left and right to NULL.
Step 2 - Check whether tree is Empty.
Step 3 - If the tree is Empty, then set root to newNode.
Step 4 - If the tree is Not Empty, then check whether the value of newNode is smaller or larger than the
node (here it is root node).
Step 5 - If newNode is smaller than or equal to the node then move to its left child. If newNode is larger
than the node then move to its right child.
Step 6- Repeat the above steps until we reach to the leaf node (i.e., reaches to NULL).
Step 7 - After reaching the leaf node, insert the newNode as left child if the newNode is smaller or equal
to that leaf node or else insert it as right child.

DELETE OPERATION

LEAF NODE

Step 1 - Find the node to be deleted using search operation


Step 2 - Delete the node using free function (If it is a leaf) and terminate the function.

SINGLE CHILD NODE

Step 1 - Find the node to be deleted using search operation


Step 2 - If it has only one child then create a link between its parent node and child node.
Step 3 - Delete the node using free function and terminate the function.

TWO CHILD NODE

Step 1 - Find the node to be deleted using search operation


Step 2 - If it has two children, then find the largest node in its left subtree (OR) the smallest node in its
right subtree.
Step 3 - Swap both deleting node and node which is found in the above step.
Step 4 - Then check whether deleting node came to case 1 or case 2 or else goto step 2
Step 5 - If it comes to case 1, then delete using case 1 logic.
Step 6- If it comes to case 2, then delete using case 2 logic.
Step 7 - Repeat the same process until the node is deleted from the tree.
PROGRAM

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

struct node
{
int key;
struct node *left, *right;
};

// A utility function to create a new BST node


struct node *newNode(int item)
{
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}

// A utility function to do inorder traversal of BST


void inorder(struct node *root)
{
if (root != NULL)
{
inorder(root->left);
printf("%d \n", root->key);
inorder(root->right);
}
}

/* A utility function to insert a new node with given key in BST */


struct node* insert(struct node* node, int key)
{
/* If the tree is empty, return a new node */
if (node == NULL) return newNode(key);

/* Otherwise, recur down the tree */


if (key < node->key)
node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);

/* return the (unchanged) node pointer */


return node;
}

// Driver Program to test above functions


int main()
{

struct node *root = NULL;


root = insert(root, 50);
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
insert(root, 60);
insert(root, 80);

// print inoder traversal of the BST


inorder(root);

return 0;
}

OUTPUT
WEEK-7

AIM: Write a program to implement AVL Trees


a) Creation b) Insertion c) Deletion

ALGORITHM

Algorithm for avl:-


For insertion:-
Step 1: First, insert a new element into the tree using BST's (Binary Search Tree) insertion logic.
Step 2: After inserting the elements you have to check the Balance Factor of each node.
Step 3: When the Balance Factor of every node will be found like 0 or 1 or -1 then the algorithm will
proceed for the next operation.
Step 4: When the balance factor of any node comes other than the above three values then the tree is
said to be imbalanced. Then perform the suitable Rotation to make it balanced and then the algorithm
will proceed for the next operation.
For Deletion:
Step 1: Firstly, find that node where k is stored
Step 2: Secondly delete those contents of the node (Suppose the node is x)
Step 3: Claim: Deleting a node in an AVL tree can be reduced by deleting a leaf. There are three possible
cases:
When x has no children then, delete x
When x has one child, let x' becomes the child of x.
Notice: x' cannot have a child, since subtrees of T can differ in height by at most one :
then replace the contents of x with the contents of x'
then delete x' (a leaf)
Step 4: When x has two children,
then find x's successor z (which has no left child)
then replace x's contents with z's contents, and
delete z
In all of the three cases, you will end up removing a leaf.

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;
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)
{
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)
{
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)
if(BF(T->right)<=0)
T=RR(T);
else
T=RL(T);
}
else
{
if(T->right!=NULL)
{
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)
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
WEEK-8

AIM: Write a program to create a Red-black tree for the given elements.

ALGORITHM

INSERT OPERATION

Step 1 - Check whether tree is Empty.


Step 2 - If tree is Empty then insert the newNode as Root node with color Black and exit from the
operation.
Step 3 - If tree is not Empty then insert the newNode as leaf node with color Red.
Step 4 - If the parent of newNode is Black then exit from the operation.
Step 5 - If the parent of newNode is Red then check the color of parentnode's sibling of newNode.
Step 6 - If it is colored Black or NULL then make suitable Rotation and Recolor it.
Step 7 - If it is colored Red then perform Recolor. Repeat the same until tree becomes Red Black Tree.

PROGRAM

#include <stdio.h>
#include <stdlib.h>
enum nodeColor
{
RED,
BLACK
};
struct rbNode
{
int data, color;
struct rbNode *link[2];
};
struct rbNode *root = NULL;
struct rbNode *createNode(int data)
{
struct rbNode *newnode;
newnode = (struct rbNode *)malloc(sizeof(struct rbNode));
newnode->data = data;
newnode->color = RED;
newnode->link[0] = newnode->link[1] = NULL;
return newnode;
}
void insertion(int data)
{
struct rbNode *stack[98], *ptr, *newnode, *xPtr, *yPtr;
int dir[98], ht = 0, index;
ptr = root;
if (!root)
{
root = createNode(data);
return;
}
stack[ht] = root;
dir[ht++] = 0;
while (ptr != NULL)
{
if (ptr->data == data)
{
printf("Duplicates Not Allowed!!\n");
return;
}
index = (data - ptr->data) > 0 ? 1 : 0;
stack[ht] = ptr;
ptr = ptr->link[index];
dir[ht++] = index;
}
stack[ht - 1]->link[index] = newnode = createNode(data);
while ((ht >= 3) && (stack[ht - 1]->color == RED))
{
if (dir[ht - 2] == 0)
{
yPtr = stack[ht - 2]->link[1];
if (yPtr != NULL && yPtr->color == RED)
{
stack[ht - 2]->color = RED;
stack[ht - 1]->color = yPtr->color = BLACK;
ht = ht - 2;
}
else
{
if (dir[ht - 1] == 0)
{
yPtr = stack[ht - 1];
}
else
{
xPtr = stack[ht - 1];
yPtr = xPtr->link[1];
xPtr->link[1] = yPtr->link[0];
yPtr->link[0] = xPtr;
stack[ht - 2]->link[0] = yPtr;
}
xPtr = stack[ht - 2];
xPtr->color = RED;
yPtr->color = BLACK;
xPtr->link[0] = yPtr->link[1];
yPtr->link[1] = xPtr;
if (xPtr == root)
{
root = yPtr;
}
else
{
stack[ht - 3]->link[dir[ht - 3]] = yPtr;
}
break;
}
}
else
{
yPtr = stack[ht - 2]->link[0];
if ((yPtr != NULL) && (yPtr->color == RED))
{
stack[ht - 2]->color = RED;
stack[ht - 1]->color = yPtr->color = BLACK;
ht = ht - 2;
}
else
{
if (dir[ht - 1] == 1)
{
yPtr = stack[ht - 1];
}
else
{
xPtr = stack[ht - 1];
yPtr = xPtr->link[0];
xPtr->link[0] = yPtr->link[1];
yPtr->link[1] = xPtr;
stack[ht - 2]->link[1] = yPtr;
}
xPtr = stack[ht - 2];
yPtr->color = BLACK;
xPtr->color = RED;
xPtr->link[1] = yPtr->link[0];
yPtr->link[0] = xPtr;
if (xPtr == root)
{
root = yPtr;
}
else
{
stack[ht - 3]->link[dir[ht - 3]] = yPtr;
}
break;
}
}
}
root->color = BLACK;
}
void deletion(int data)
{
struct rbNode *stack[98], *ptr, *xPtr, *yPtr;
struct rbNode *pPtr, *qPtr, *rPtr;
int dir[98], ht = 0, diff, i;
enum nodeColor color;
if (!root)
{
printf("Tree not available\n");
return;
}
ptr = root;
while (ptr != NULL)
{
if ((data - ptr->data) == 0)
break;
diff = (data - ptr->data) > 0 ? 1 : 0;
stack[ht] = ptr;
dir[ht++] = diff;
ptr = ptr->link[diff];
}
if (ptr->link[1] == NULL)
{
if ((ptr == root) && (ptr->link[0] == NULL))
{
free(ptr);
root = NULL;
}
else if (ptr == root)
{
root = ptr->link[0];
free(ptr);
}
else
{
stack[ht - 1]->link[dir[ht - 1]] = ptr->link[0];
}
}
else
{
xPtr = ptr->link[1];
if (xPtr->link[0] == NULL)
{
xPtr->link[0] = ptr->link[0];
color = xPtr->color;
xPtr->color = ptr->color;
ptr->color = color;
if (ptr == root)
{
root = xPtr;
}
else
{
stack[ht - 1]->link[dir[ht - 1]] = xPtr;
}
dir[ht] = 1;
stack[ht++] = xPtr;
}
else
{
i = ht++;
while (1)
{
dir[ht] = 0;
stack[ht++] = xPtr;
yPtr = xPtr->link[0];
if (!yPtr->link[0])
break;
xPtr = yPtr;
}
dir[i] = 1;
stack[i] = yPtr;
if (i > 0)
stack[i - 1]->link[dir[i - 1]] = yPtr;
yPtr->link[0] = ptr->link[0];
xPtr->link[0] = yPtr->link[1];
yPtr->link[1] = ptr->link[1];
if (ptr == root)
{
root = yPtr;
}
color = yPtr->color;
yPtr->color = ptr->color;
ptr->color = color;
}
}
if (ht < 1)
return;
if (ptr->color == BLACK)
{
while (1)
{
pPtr = stack[ht - 1]->link[dir[ht - 1]];
if (pPtr && pPtr->color == RED)
{
pPtr->color = BLACK;
break;
}
if (ht < 2)
break;
if (dir[ht - 2] == 0)
{
rPtr = stack[ht - 1]->link[1];
if (!rPtr)
break;
if (rPtr->color == RED)
{
stack[ht - 1]->color = RED;
rPtr->color = BLACK;
stack[ht - 1]->link[1] = rPtr->link[0];
rPtr->link[0] = stack[ht - 1];
if (stack[ht - 1] == root)
{
root = rPtr;
}
else
{
stack[ht - 2]->link[dir[ht - 2]] = rPtr;
}
dir[ht] = 0;
stack[ht] = stack[ht - 1];
stack[ht - 1] = rPtr;
ht++;
rPtr = stack[ht - 1]->link[1];
}
if ((!rPtr->link[0] || rPtr->link[0]->color == BLACK) &&
(!rPtr->link[1] || rPtr->link[1]->color == BLACK))
{
rPtr->color = RED;
}
else
{
if (!rPtr->link[1] || rPtr->link[1]->color == BLACK)
{
qPtr = rPtr->link[0];
rPtr->color = RED;
qPtr->color = BLACK;
rPtr->link[0] = qPtr->link[1];
qPtr->link[1] = rPtr;
rPtr = stack[ht - 1]->link[1] = qPtr;
}
rPtr->color = stack[ht - 1]->color;
stack[ht - 1]->color = BLACK;
rPtr->link[1]->color = BLACK;
stack[ht - 1]->link[1] = rPtr->link[0];
rPtr->link[0] = stack[ht - 1];
if (stack[ht - 1] == root)
{
root = rPtr;
}
else
{
stack[ht - 2]->link[dir[ht - 2]] = rPtr;
}
break;
}
}
else
{
rPtr = stack[ht - 1]->link[0];
if (!rPtr)
break;
if (rPtr->color == RED)
{
stack[ht - 1]->color = RED;
rPtr->color = BLACK;
stack[ht - 1]->link[0] = rPtr->link[1];
rPtr->link[1] = stack[ht - 1];
if (stack[ht - 1] == root)
{
root = rPtr;
}
else
{
stack[ht - 2]->link[dir[ht - 2]] = rPtr;
}
dir[ht] = 1;
stack[ht] = stack[ht - 1];
stack[ht - 1] = rPtr;
ht++;
rPtr = stack[ht - 1]->link[0];
}
if ((!rPtr->link[0] || rPtr->link[0]->color == BLACK) &&
(!rPtr->link[1] || rPtr->link[1]->color == BLACK))
{
rPtr->color = RED;
}
else
{
if (!rPtr->link[0] || rPtr->link[0]->color == BLACK)
{
qPtr = rPtr->link[1];
rPtr->color = RED;
qPtr->color = BLACK;
rPtr->link[1] = qPtr->link[0];
qPtr->link[0] = rPtr;
rPtr = stack[ht - 1]->link[0] = qPtr;
}
rPtr->color = stack[ht - 1]->color;
stack[ht - 1]->color = BLACK;
rPtr->link[0]->color = BLACK;
stack[ht - 1]->link[0] = rPtr->link[1];
rPtr->link[1] = stack[ht - 1];
if (stack[ht - 1] == root)
{
root = rPtr;
}
else
{
stack[ht - 2]->link[dir[ht - 2]] = rPtr;
}
break;
}
}
ht--;
}
}
}
void inorderTraversal(struct rbNode *node)
{
if (node)
{
inorderTraversal(node->link[0]);
printf("%d ", node->data);
inorderTraversal(node->link[1]);
}
return;
}
int main()
{
int ch, data;
while (1)
{
printf("1. Insertion\t2. Deletion\n");
printf("3. Traverse\t4. Exit");
printf("\nEnter your choice:");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("Enter the element to insert:");
scanf("%d", &data);
insertion(data);
break;
case 2:
printf("Enter the element to delete:");
scanf("%d", &data);
deletion(data);
break;
case 3:
inorderTraversal(root);
printf("\n");
break;
case 4:
exit(0);
default:
printf("Not available\n");
break;
}
printf("\n");
}
return 0;
}

OUTPUT
WEEK-9

AIM: Write a program to create a splay tree for the given elements.

ALGORITHM

Step 1 - Check whether tree is Empty.


Step 2 - If tree is Empty then insert the newNode as Root node and exit from the operation.
Step 3 - If tree is not Empty then insert the newNode as leaf node using Binary Search tree insertion
logic.
Step 4 - After insertion, Splay the newNode.

PROGRAM

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

typedef struct node {


int data;
struct node *left;
struct node *right;
struct node *parent;
}node;

typedef struct splay_tree {


struct node *root;
}splay_tree;

node* new_node(int data) {


node *n = malloc(sizeof(node));
n->data = data;
n->parent = NULL;
n->right = NULL;
n->left = NULL;

return n;
}

splay_tree* new_splay_tree() {
splay_tree *t = malloc(sizeof(splay_tree));
t->root = NULL;

return t;
}

node* maximum(splay_tree *t, node *x) {


while(x->right != NULL)
x = x->right;
return x;
}

void left_rotate(splay_tree *t, node *x) {


node *y = x->right;
x->right = y->left;
if(y->left != NULL) {
y->left->parent = x;
}
y->parent = x->parent;
if(x->parent == NULL) { //x is root
t->root = y;
}
else if(x == x->parent->left) { //x is left child
x->parent->left = y;
}
else { //x is right child
x->parent->right = y;
}
y->left = x;
x->parent = y;
}

void right_rotate(splay_tree *t, node *x) {


node *y = x->left;
x->left = y->right;
if(y->right != NULL) {
y->right->parent = x;
}
y->parent = x->parent;
if(x->parent == NULL) { //x is root
t->root = y;
}
else if(x == x->parent->right) { //x is left child
x->parent->right = y;
}
else { //x is right child
x->parent->left = y;
}
y->right = x;
x->parent = y;
}

void splay(splay_tree *t, node *n) {


while(n->parent != NULL) { //node is not root
if(n->parent == t->root) { //node is child of root, one rotation
if(n == n->parent->left) {
right_rotate(t, n->parent);
}
else {
left_rotate(t, n->parent);
}
}
else {
node *p = n->parent;
node *g = p->parent; //grandparent

if(n->parent->left == n && p->parent->left == p) { //both are left children


right_rotate(t, g);
right_rotate(t, p);
}
else if(n->parent->right == n && p->parent->right == p) { //both are right children
left_rotate(t, g);
left_rotate(t, p);
}
else if(n->parent->right == n && p->parent->left == p) {
left_rotate(t, p);
right_rotate(t, g);
}
else if(n->parent->left == n && p->parent->right == p) {
right_rotate(t, p);
left_rotate(t, g);
}
}
}
}

void insert(splay_tree *t, node *n) {


node *y = NULL;
node *temp = t->root;
while(temp != NULL) {
y = temp;
if(n->data < temp->data)
temp = temp->left;
else
temp = temp->right;
}
n->parent = y;

if(y == NULL) //newly added node is root


t->root = n;
else if(n->data < y->data)
y->left = n;
else
y->right = n;
splay(t, n);
}

node* search(splay_tree *t, node *n, int x) {


if(x == n->data) {
splay(t, n);
return n;
}
else if(x < n->data)
return search(t, n->left, x);
else if(x > n->data)
return search(t, n->right, x);
else
return NULL;
}

void delete(splay_tree *t, node *n) {


splay(t, n);

splay_tree *left_subtree = new_splay_tree();


left_subtree->root = t->root->left;
if(left_subtree->root != NULL)
left_subtree->root->parent = NULL;

splay_tree *right_subtree = new_splay_tree();


right_subtree->root = t->root->right;
if(right_subtree->root != NULL)
right_subtree->root->parent = NULL;

free(n);

if(left_subtree->root != NULL) {
node *m = maximum(left_subtree, left_subtree->root);
splay(left_subtree, m);
left_subtree->root->right = right_subtree->root;
t->root = left_subtree->root;
}
else {
t->root = right_subtree->root;
}
}

void inorder(splay_tree *t, node *n) {


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

int main() {
splay_tree *t = new_splay_tree();

node *a, *b, *c, *d, *e, *f, *g, *h, *i, *j, *k, *l, *m;
a = new_node(10);
b = new_node(20);
c = new_node(30);
d = new_node(100);
e = new_node(90);
f = new_node(40);
g = new_node(50);
h = new_node(60);
i = new_node(70);
j = new_node(80);
k = new_node(150);
l = new_node(110);
m = new_node(120);

insert(t, a);
insert(t, b);
insert(t, c);
insert(t, d);
insert(t, e);
insert(t, f);
insert(t, g);
insert(t, h);
insert(t, i);
insert(t, j);
insert(t, k);
insert(t, l);
insert(t, m);

delete(t, a);
delete(t, m);

inorder(t, t->root);

return 0;
}
OUTPUT
WEEK-10

AIM: Write a program for Boyer-Moore pattern matching algorithm.

ALGORITHM

BOYER_MOORE_MATCHER (T, P)

Input: Text with n characters and Pattern with m characters


Output: Index of the first substring of T matching P

Compute function last


i ← m-1
j ← m-1
Repeat
If P[j] = T[i] then
if j=0 then
return i // we have a match
else
i ← i -1
j ← j -1
else
i ← i + m - Min(j, 1 + last[T[i]])
j ← m -1
until i > n -1
Return "no match"

PROGRAM

# include <limits.h>
# include <string.h>
# include <stdio.h>
# define NO_OF_CHARS 256
int max (int a, int b) { return (a > b)? a: b; }
void badCharHeuristic( char *str, int size,
int badchar[NO_OF_CHARS])
{
int i;
for (i = 0; i < NO_OF_CHARS; i++)
badchar[i] = -1;
for (i = 0; i < size; i++)
badchar[(int) str[i]] = i;
}
void search( char *txt, char *pat)
{
int m = strlen(pat);
int n = strlen(txt);
int badchar[NO_OF_CHARS];
badCharHeuristic(pat, m, badchar);
int s = 0;
while(s <= (n - m))
{
int j = m-1;
while(j >= 0 && pat[j] == txt[s+j])
j--;
if (j < 0)
{
printf("\n pattern occurs at shift = %d", s);
s += (s+m < n)? m-badchar[txt[s+m]] : 1;

else
s += max(1, j - badchar[txt[s+j]]);
}
}
int main()
{
char txt[] = "ABAAABCD";
char pat[] = "ABC";
search(txt, pat);
return 0;
}

output:
WEEK-11

AIM: Write a program to implement KMP pattern matching Algorithm.

ALGORITHM:

Step 1: Initialize the input variables :


n = Length of the Text .
m = Length of the Pattern.
u = Prefix−function of pattern(p) .
q = Number of characters matched .
Step 2: Define the variable :
q=0 , the beginning of the match .
Step 3: Compare the first character of the pattern with first character of text.
I f match i s not found , substitute the value of u[q] to q .
I f match i s found , then increment the value of q by 1.
Step 4: Check whether all the pattern elements are matched w ith the text
elements .
I f not , repeat the search process .
I f yes , print the number of shifts taken by the pattern .
Step 5: look for the next match .

PROGRAM

#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
char string[100], matchcase[20], c;
int i = 0, j = 0, index;
/*Scanning string*/
printf("Enter string: ");
do
{
fflush(stdin);
c = getchar();
string[i++] = tolower(c);

} while (c != '\n');
string[i - 1] = '\0';
/*Scanning substring*/
printf("Enter substring: ");
i = 0;
do
{
fflush(stdin);
c = getchar();
matchcase[i++] = tolower(c);
} while (c != '\n');
matchcase[i - 1] = '\0';
for (i = 0; i < strlen(string) - strlen(matchcase) + 1; i++)
{
index = i;
if (string[i] == matchcase[j])
{
do
{
i++;
j++;
} while(j != strlen(matchcase) && string[i] == matchcase[j]);
if (j == strlen(matchcase))
{
printf("Match found from position %d to %d.\n", index + 1, i);
return 0;
}
else
{
i = index + 1;
j = 0;
}
}
}
printf("No substring match found in the string.\n");
return 0;
}

Output:-
WEEK-12

AIM: Write a program to create a Kd tree for the given element.

PROGRAM

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#define MAX_DIM 3
struct kd_node_t{
double x[MAX_DIM];
struct kd_node_t *left, *right;
};

inline double
dist(struct kd_node_t *a, struct kd_node_t *b, int dim)
{
double t, d = 0;
while (dim--) {
t = a->x[dim] - b->x[dim];
d += t * t;
}
return d;
}
inline void swap(struct kd_node_t *x, struct kd_node_t *y) {
double tmp[MAX_DIM];
memcpy(tmp, x->x, sizeof(tmp));
memcpy(x->x, y->x, sizeof(tmp));
memcpy(y->x, tmp, sizeof(tmp));
}

/* see quickselect method */


struct kd_node_t*
find_median(struct kd_node_t *start, struct kd_node_t *end, int idx)
{
if (end <= start) return NULL;
if (end == start + 1)
return start;

struct kd_node_t *p, *store, *md = start + (end - start) / 2;


double pivot;
while (1) {
pivot = md->x[idx];
swap(md, end - 1);
for (store = p = start; p < end; p++) {
if (p->x[idx] < pivot) {
if (p != store)
swap(p, store);
store++;
}
}
swap(store, end - 1);

/* median has duplicate values */


if (store->x[idx] == md->x[idx])
return md;

if (store > md) end = store;


else start = store;
}
}

struct kd_node_t*
make_tree(struct kd_node_t *t, int len, int i, int dim)
{
struct kd_node_t *n;

if (!len) return 0;

if ((n = find_median(t, t + len, i))) {


i = (i + 1) % dim;
n->left = make_tree(t, n - t, i, dim);
n->right = make_tree(n + 1, t + len - (n + 1), i, dim);
}
return n;
}

/* global variable, so sue me */


int visited;

void nearest(struct kd_node_t *root, struct kd_node_t *nd, int i, int dim,
struct kd_node_t **best, double *best_dist)
{
double d, dx, dx2;

if (!root) return;
d = dist(root, nd, dim);
dx = root->x[i] - nd->x[i];
dx2 = dx * dx;

visited ++;
if (!*best || d < *best_dist) {
*best_dist = d;
*best = root;
}

/* if chance of exact match is high */


if (!*best_dist) return;

if (++i >= dim) i = 0;

nearest(dx > 0 ? root->left : root->right, nd, i, dim, best, best_dist);


if (dx2 >= *best_dist) return;
nearest(dx > 0 ? root->right : root->left, nd, i, dim, best, best_dist);
}

#define N 1000000
#define rand1() (rand() / (double)RAND_MAX)
#define rand_pt(v) { v.x[0] = rand1(); v.x[1] = rand1(); v.x[2] = rand1(); }
int main(void)
{
int i;
struct kd_node_t wp[] = {
{{2, 3}}, {{5, 4}}, {{9, 6}}, {{4, 7}}, {{8, 1}}, {{7, 2}}
};
struct kd_node_t testNode = {{9, 2}};
struct kd_node_t *root, *found, *million;
double best_dist;

root = make_tree(wp, sizeof(wp) / sizeof(wp[1]), 0, 2);

visited = 0;
found = 0;
nearest(root, &testNode, 0, 2, &found, &best_dist);

printf(">> WP tree\nsearching for (%g, %g)\n"


"found (%g, %g) dist %g\nseen %d nodes\n\n",
testNode.x[0], testNode.x[1],
found->x[0], found->x[1], sqrt(best_dist), visited);

million =(struct kd_node_t*) calloc(N, sizeof(struct kd_node_t));


srand(time(0));
for (i = 0; i < N; i++) rand_pt(million[i]);

root = make_tree(million, N, 0, 3);


rand_pt(testNode);

visited = 0;
found = 0;
nearest(root, &testNode, 0, 3, &found, &best_dist);

printf(">> Million tree\nsearching for (%g, %g, %g)\n"


"found (%g, %g, %g) dist %g\nseen %d nodes\n",
testNode.x[0], testNode.x[1], testNode.x[2],
found->x[0], found->x[1], found->x[2],
sqrt(best_dist), visited);

/* search many random points in million tree to see average behavior.


tree size vs avg nodes visited:
10 ~ 7
100 ~ 16.5
1000 ~ 25.5
10000 ~ 32.8
100000 ~ 38.3
1000000 ~ 42.6
10000000 ~ 46.7 */
int sum = 0, test_runs = 100000;
for (i = 0; i < test_runs; i++) {
found = 0;
visited = 0;
rand_pt(testNode);
nearest(root, &testNode, 0, 3, &found, &best_dist);
sum += visited;
}
printf("\n>> Million tree\n"
"visited %d nodes for %d random findings (%f per lookup)\n",
sum, test_runs, sum/(double)test_runs);

// free(million);

return 0;
}

OUTPUT:
WEEK-13

AIM: Write a program to construct a binomial heap for the given elements.

PROGRAM:
#include<stdio.h>
#include<malloc.h>
struct node {
int n;
int degree;
struct node* parent;
struct node* child;
struct node* sibling;
};

struct node* MAKE_bin_HEAP();


int bin_LINK(struct node*, struct node*);
struct node* CREATE_NODE(int);
struct node* bin_HEAP_UNION(struct node*, struct node*);
struct node* bin_HEAP_INSERT(struct node*, struct node*);
struct node* bin_HEAP_MERGE(struct node*, struct node*);
struct node* bin_HEAP_EXTRACT_MIN(struct node*);
int REVERT_LIST(struct node*);
int DISPLAY(struct node*);
struct node* FIND_NODE(struct node*, int);
int bin_HEAP_DECREASE_KEY(struct node*, int, int);
int bin_HEAP_DELETE(struct node*, int);

int count = 1;

struct node* MAKE_bin_HEAP() {


struct node* np;
np = NULL;
return np;
}

struct node * H = NULL;


struct node *Hr = NULL;

int bin_LINK(struct node* y, struct node* z) {


y->parent = z;
y->sibling = z->child;
z->child = y;
z->degree = z->degree + 1;
}

struct node* CREATE_NODE(int k) {


struct node* p;//new node;
p = (struct node*) malloc(sizeof(struct node));
p->n = k;
return p;
}

struct node* bin_HEAP_UNION(struct node* H1, struct node* H2) {


struct node* prev_x;
struct node* next_x;
struct node* x;
struct node* H = MAKE_bin_HEAP();
H = bin_HEAP_MERGE(H1, H2);
if (H == NULL)
return H;
prev_x = NULL;
x = H;
next_x = x->sibling;
while (next_x != NULL) {
if ((x->degree != next_x->degree) || ((next_x->sibling != NULL)
&& (next_x->sibling)->degree == x->degree)) {
prev_x = x;
x = next_x;
} else {
if (x->n <= next_x->n) {
x->sibling = next_x->sibling;
bin_LINK(next_x, x);
} else {
if (prev_x == NULL)
H = next_x;
else
prev_x->sibling = next_x;
bin_LINK(x, next_x);
x = next_x;
}
}
next_x = x->sibling;
}
return H;
}

struct node* bin_HEAP_INSERT(struct node* H, struct node* x) {


struct node* H1 = MAKE_bin_HEAP();
x->parent = NULL;
x->child = NULL;
x->sibling = NULL;
x->degree = 0;
H1 = x;
H = bin_HEAP_UNION(H, H1);
return H;
}

struct node* bin_HEAP_MERGE(struct node* H1, struct node* H2) {


struct node* H = MAKE_bin_HEAP();
struct node* y;
struct node* z;
struct node* a;
struct node* b;
y = H1;
z = H2;
if (y != NULL) {
if (z != NULL && y->degree <= z->degree)
H = y;
else if (z != NULL && y->degree > z->degree)
/* need some modifications here;the first and the else conditions can be merged together!!!! */
H = z;
else
H = y;
} else
H = z;
while (y != NULL && z != NULL) {
if (y->degree < z->degree) {
y = y->sibling;
} else if (y->degree == z->degree) {
a = y->sibling;
y->sibling = z;
y = a;
} else {
b = z->sibling;
z->sibling = y;
z = b;
}
}
return H;
}

int DISPLAY(struct node* H) {


struct node* p;
if (H == NULL) {
printf("\nHEAP EMPTY");
return 0;
}
printf("\nTHE ROOT NODES ARE:-\n");
p = H;
while (p != NULL) {
printf("%d", p->n);
if (p->sibling != NULL)
printf("-->");
p = p->sibling;
}
printf("\n");
}

struct node* bin_HEAP_EXTRACT_MIN(struct node* H1) {


int min;
struct node* t = NULL;
struct node* x = H1;
struct node *Hr;
struct node* p;
Hr = NULL;
if (x == NULL) {
printf("\nNOTHING TO EXTRACT");
return x;
}
// int min=x->n;
p = x;
while (p->sibling != NULL) {
if ((p->sibling)->n < min) {
min = (p->sibling)->n;
t = p;
x = p->sibling;
}
p = p->sibling;
}
if (t == NULL && x->sibling == NULL)
H1 = NULL;
else if (t == NULL)
H1 = x->sibling;
else if (t->sibling == NULL)
t = NULL;
else
t->sibling = x->sibling;
if (x->child != NULL) {
REVERT_LIST(x->child);
(x->child)->sibling = NULL;
}
H = bin_HEAP_UNION(H1, Hr);
return x;
}

int REVERT_LIST(struct node* y) {


if (y->sibling != NULL) {
REVERT_LIST(y->sibling);
(y->sibling)->sibling = y;
} else {
Hr = y;
}
}

struct node* FIND_NODE(struct node* H, int k) {


struct node* x = H;
struct node* p = NULL;
if (x->n == k) {
p = x;
return p;
}
if (x->child != NULL && p == NULL) {
p = FIND_NODE(x->child, k);
}

if (x->sibling != NULL && p == NULL) {


p = FIND_NODE(x->sibling, k);
}
return p;
}

int bin_HEAP_DECREASE_KEY(struct node* H, int i, int k) {


int temp;
struct node* p;
struct node* y;
struct node* z;
p = FIND_NODE(H, i);
if (p == NULL) {
printf("\nINVALID CHOICE OF KEY TO BE REDUCED");
return 0;
}
if (k > p->n) {
printf("\nSORY!THE NEW KEY IS GREATER THAN CURRENT ONE");
return 0;
}
p->n = k;
y = p;
z = p->parent;
while (z != NULL && y->n < z->n) {
temp = y->n;
y->n = z->n;
z->n = temp;
y = z;
z = z->parent;
}
printf("\nKEY REDUCED SUCCESSFULLY!");
}
int bin_HEAP_DELETE(struct node* H, int k) {
struct node* np;
if (H == NULL) {
printf("\nHEAP EMPTY");
return 0;
}

bin_HEAP_DECREASE_KEY(H, k, -1000);
np = bin_HEAP_EXTRACT_MIN(H);
if (np != NULL)
printf("\nNODE DELETED SUCCESSFULLY");
}

int main() {
int i, n, m, l;
struct node* p;
struct node* np;
char ch;
printf("\nENTER THE NUMBER OF ELEMENTS:");
scanf("%d", &n);
printf("\nENTER THE ELEMENTS:\n");
for (i = 1; i <= n; i++) {
scanf("%d", &m);
np = CREATE_NODE(m);
H = bin_HEAP_INSERT(H, np);
}
DISPLAY(H);
do {
printf("\nMENU:-\n");
printf(
"\n1)INSERT AN ELEMENT\n2)EXTRACT THE MINIMUM KEY NODE\n3)DECREASE A NODE KEY\n
4)DELETE A NODE\n5)QUIT\n");
scanf("%d", &l);
switch (l) {
case 1:
do {
printf("\nENTER THE ELEMENT TO BE INSERTED:");
scanf("%d", &m);
p = CREATE_NODE(m);
H = bin_HEAP_INSERT(H, p);
printf("\nNOW THE HEAP IS:\n");
DISPLAY(H);
printf("\nINSERT MORE(y/Y)= \n");
fflush(stdin);
scanf("%c", &ch);
} while (ch == 'Y' || ch == 'y');
break;
case 2:
do {
printf("\nEXTRACTING THE MINIMUM KEY NODE");
p = bin_HEAP_EXTRACT_MIN(H);
if (p != NULL)
printf("\nTHE EXTRACTED NODE IS %d", p->n);
printf("\nNOW THE HEAP IS:\n");
DISPLAY(H);
printf("\nEXTRACT MORE(y/Y)\n");
fflush(stdin);
scanf("%c", &ch);
} while (ch == 'Y' || ch == 'y');
break;
case 3:
do {
printf("\nENTER THE KEY OF THE NODE TO BE DECREASED:");
scanf("%d", &m);
printf("\nENTER THE NEW KEY : ");
scanf("%d", &l);
bin_HEAP_DECREASE_KEY(H, m, l);
printf("\nNOW THE HEAP IS:\n");
DISPLAY(H);
printf("\nDECREASE MORE(y/Y)\n");
fflush(stdin);
scanf("%c", &ch);
} while (ch == 'Y' || ch == 'y');
break;
case 4:
do {
printf("\nENTER THE KEY TO BE DELETED: ");
scanf("%d", &m);
bin_HEAP_DELETE(H, m);
printf("\nDELETE MORE(y/Y)\n");
fflush(stdin);
scanf("%c", &ch);
} while (ch == 'y' || ch == 'Y');
break;
case 5:
printf("\nTHANK U SIR\n");
break;
default:
printf("\nINVALID ENTRY...TRY AGAIN....\n");
}
} while (l != 5);
}
OUTPUT:
ENTER THE NUMBER OF ELEMENTS:5
ENTER THE ELEMENTS:12 23 34 45 56
THE ROOT NODES ARE:-
56-->12

MENU:-

1)INSERT AN ELEMENT
2)EXTRACT THE MINIMUM KEY NODE
3)DECREASE A NODE KEY
4)DELETE A NODE
5)QUIT
1
ENTER THE ELEMENT TO BE INSERTED:67
NOW THE HEAP IS:

THE ROOT NODES ARE:-


56-->12

INSERT MORE(y/Y)= n

MENU:-

1)INSERT AN ELEMENT
2)EXTRACT THE MINIMUM KEY NODE
3)DECREASE A NODE KEY
4)DELETE A NODE
5)QUIT

ENTER THE ELEMENT TO BE DELETED:67


NOW THE HEAP IS:

THE ROOT NODES ARE:-


67-->56-->12

DELETE MORE(y/Y)= n

MENU:-

1)INSERT AN ELEMENT
2)EXTRACT THE MINIMUM KEY NODE
3)DECREASE A NODE KEY
4)DELETE A NODE
5)QUIT

You might also like