Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 67

CS22312 - DATA STRUCTURES LABORATORY

EX.NO: 1
DATE:

Study of simple node creation using pointers, structures and study of functions.

AIM:
To perform Study Of concept of programming prerequisite Functions, Structures, union,
pointers, arrays and to Create Node Using Pointers, Structures.

ALGORITHM:

1. Include the necessary header files


2. Define a structure `struct StudentData`:
- Define a structure named `StudentData` with three members:
- `stu_name`: A character pointer (string) to store the student's name.
- `stu_id`: An integer to store the student's ID.
- `stu_age`: An integer to store the student's age.
3. Define a union `union un`:
- Define a union named `un` with three members:
- `member1`: An integer.
- `member2`: A character.
- `member3`: A floating-point number (float).
4. Define the `main` function, which serves as the program's entry point:
- Declare a variable of type `struct StudentData` named `student`.
- Assign values to the members of the `student` structure:
- Set `student.stu_name` to "Steve" using a string literal.
- Set `student.stu_id` to 1234.
- Set `student.stu_age` to 30.
- Use `printf` statements to print the student's name, ID, and age.
5. Declare a variable of type `union un` named `var1`.
6. Assign a value to the `member1` member of the `var1` union: - Set `var1.member1`
to 15.
7. Use a `printf` statement to print the value stored in `var1.member1`.
8. Return 0 to indicate successful program execution.
9. End the `main` function.

PROGRAM:
#include <stdio.h>
struct StudentData{
char *stu_name;
int stu_id;
int stu_age;
};
union un {

ROLL NO: 2127220501175 PAGE NO: 1


int member1;
char member2;
float member3;
};
int main()
{
struct StudentData student;
student.stu_name = "Steve";
student.stu_id = 1234;
student.stu_age = 30;
printf("Student Name is: %s", student.stu_name);
printf("\nStudent Id is: %d", student.stu_id);
printf("\nStudent Age is: %d", student.stu_age);
union un var1;
var1.member1 = 15;
printf("\n The value stored in member1 = %d",
var1.member1);
return 0;
}

SAMPLE OUTPUT:

RESULT:
Thus the Study Of concept of programming prerequisite Functions, Structures, union,
pointers, arrays and to Create Node Using Pointers, Structures has been executed and
compiled successfully.

ROLL NO: 2127220501175 PAGE NO: 2


CS22312 - DATA STRUCTURES LABORATORY
EX.NO: 2.1
DATE:

Implementation of singly linked list using array

AIM:
To understand one of the most basic data structures called array. This will help the
studentsas a pre-requisite for most of the complex data structures.

ALGORITHM:

1. Include the necessary header files


2. Define a constant `MAX` with a value of 10 to represent the maximum number
of elements in the list.
3. Define a structure to hold the list and related information: - This structure includes
the following members:
- `list`: An integer array of size `MAX` to store the elements.
- `element`: An integer to temporarily hold an element.
- `pos`: An integer to temporarily hold a position.
- `length`: An integer to keep track of the number of elements in the list.
4. Define an enumeration `enum boolean` to represent boolean values (true and
false) using `true` and `false`.
5. Define function prototypes for various list operations:
- `int menu(void)`: Display a menu and return the user's choice.
- `void create(void)`: Initialize the list by accepting elements from the user.
- `void insert(int element, int pos)`: Insert an element at the specified position.
- `void delet(int pos)`: Delete an element from the specified position.
- `void find(int element)`: Search for an element in the list.
- `void display(void)`: Display the elements in the list.
- `boolean islistfull(void)`: Check if the list is full.
- `boolean islistempty(void)`: Check if the list is empty.
6. Define the `main` function:
- Declare variables `ch`, `element`, `pos`, and initialize `l.length` to 0. - Enter an
infinite loop (`while(1)`) for displaying the menu and performing operations
based on user choices.
- Use a `switch` statement to perform various actions based on the user's
choice.
7. Implement the `menu` function:
- Display a menu of options to the user.
- Accept the user's choice and return it.
8. Implement the `create` function:
- Use a loop to accept elements from the user and add them to the list.
- Prompt the user to insert another element (`flag`).

ROLL NO: 2127220501175 PAGE NO: 3


- Continue the loop until the user decides to stop.
9. Implement the `display` function:
- Iterate through the list and display each element along with its position.
10. Implement the `insert` function:
- Check if the specified position is valid.
- Shift elements to the right to make space for the new element. - Insert
the new element at the specified position.
11. Implement the `delet` function:
- Check if the specified position is valid.
- Shift elements to the left to remove the specified element.
12. Implement the `find` function:
- Search for the specified element in the list.
- Display the position if found; otherwise, indicate that the element was
not found.
13. Implement the `islistfull` and `islistempty` functions:
- Check whether the list is full or empty based on the `length` member
of the list structure.
14. Exit the program if the user chooses the "Exit" option.
15. End the `main` function.

PROGRAM:

#include<stdio.h>
#include<stdlib.h>
#define MAX 10
struct
{
int list[MAX];
int element;
int pos;
int length;
}l;
enum boolean
{
true, false
};
typedef enum boolean boolean;
int menu(void);
void create(void);
void insert(int, int);
void delet(int);
void find(int);
void display(void);
boolean islistfull(void);
boolean islistempty(void);
void main()
{
int ch;
ROLL NO: 2127220501175 PAGE NO: 4
int element;
int pos;
l.length = 0;
while(1)
{
ch = menu();
switch (ch)
{
case 1: l.length = 0;
create();
break;
case 2:
if (islistfull() != true)
{
printf("Enter New element: ");
scanf("%d", &element);
printf("Enter the Position : ");
scanf("%d", &pos);
insert(element, pos);
}
else
{
printf("List is Full. Cannot insert the element");
printf("\n Press any key to continue...");
}
break;
case 3:
if (islistempty() != true)
{
printf("Enter the position of element to be deleted : ");
scanf("%d", &pos);
delet(pos);
}
else
{
printf("List is Empty.");
printf("\n Press any key to continue...");
}
break;
case 4:
printf("No of elements in the list is %d", l.length);
printf("\n Press any key to continue...");
break;
case 5:
printf("Enter the element to be searched :
"); scanf("%d", &element);
find(element);
break;
case 6:

ROLL NO: 2127220501175 PAGE NO: 5


display();
break;
case 7:
printf("Exit");
exit(0);
break;
default: printf("Invalid Choice");
printf("\n Press any key to continue...");
}
}
}
int menu()
{
int ch;
printf("1. Create\n2. Insert\n3. Delete\n4. Count\n5. Find\n6. Display\n7.Exit\n\n
Enter your choice : ");
scanf("%d", &ch);
printf("\n\n");
return ch;
}
void create(void)
{
int element;
int flag=1;
while(flag==1)
{
printf("Enter element : ");
scanf("%d", &element);
l.list[l.length] = element;
l.length++;
printf("To insert another element press '1' : ");
scanf("%d", &flag);
}
}
void display(void)
{
int i;
for (i=0; i<l.length; i++)
printf("Element %d : %d \n", i+1, l.list[i]);
printf("Press any key to continue...");
}
void insert(int element, int pos)
{
int i;
if (pos == 0)
{
printf("\nCannot insert an element at 0th position");
return;
}

ROLL NO: 2127220501175 PAGE NO: 6


if (pos-1 > l.length)
{
printf("\nOnly %d elements exit. Cannot insert at %d position", l.length, pos);
printf("\n Press any key to continue...");
}
else
{
for (i=l.length; i>=pos-1; i--)
{
l.list[i+1] = l.list[i];
}
l.list[pos-1] = element;
l.length++;
}
}
void delet(int pos)
{
int i;
if(pos == 0)
{
printf("\nCannot delete at an element 0th position");
return;
}
if (pos > l.length)
{
printf("\n\n Only %d elements exit. Cannot delete", l.length, pos); printf("\
n Press any key to continue...");
return;
}
for (i=pos-1; i<l.length; i++)
{
l.list[i] = l.list[i+1];
}
l.length--;
}

void find(int element)


{
int i;
int flag = 1;

for (i=0; i<l.length; i++)


{
if(l.list[i] == element)
{
printf ("%d exists at %d position",element, i+1);
flag = 0;
printf("\n Press any key to continue...");
ROLL NO: 2127220501175 PAGE NO: 7
break;
}
}
if(flag == 1)
{
printf("Element not found.\n Press any key to continue...");
}
}
boolean islistfull(void)
{
if (l.length == MAX)
return true;
else
return false;
}
boolean islistempty(void)
{
if (l.length == 0)
return true;
else
return false;
}

SAMPLE INPUT AND OUTPUT:

ROLL NO: 2127220501175 PAGE NO: 8


RESULT:
Thus the implementation of singly linked list using array has been executed and
compiled successfully.
ROLL NO: 2127220501175 PAGE NO: 9
CS22312 - DATA STRUCTURES LABORATORY
EX.NO: 2.2
DATE:

IMPLEMENTATION OF SINGLY LINKED LIST USING POINTERS &


DYNAMIC MEMORY ALLOCATION
AIM:
To implementation of singly linked list using pointers & dynamic memory allocation.

ALGORITHM:

1. Include the necessary header files


2. Define a structure `struct Node` to represent a linked list node: - It
has two members:
- `data`: An integer to store the data for the node.
- `next`: A pointer to another `struct Node`, representing the next node
in the list.
3. Define a function `newNode(int data)` to create a new linked list node:
- Allocate memory for a new node using `malloc`.
- Set the `data` member of the new node to the provided `data`.
- Initialize the `next` member to `NULL`.
- Return the newly created node.
4. Define a function `constructList()` to create and construct a linked list:
- Create three linked list nodes using `newNode`, representing elements 1, 2, and 3.
- Set up the links between these nodes:
- The `next` of the first node points to the second node.
- The `next` of the second node points to the third node.
- Set the `head` pointer to the first node.
- Return the `head` pointer, which represents the starting node of the list.
5. Define a function `printList(struct Node* head)` to print the linked list
6. In the `main` function:
- Call the `constructList()` function to create a linked list.
- Assign the returned `head` pointer to the `head` variable.
- Call the `printList()` function to print the linked list.
- Return 0 to indicate successful program execution.
7. End the `main` function.

PROGRAM:

#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node* next;
};
ROLL NO: 2127220501175 PAGE NO: 10
struct Node* newNode(int data)
{
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->next = NULL;

return node;
}
struct Node* constructList()
{
// construct three linked list nodes
struct Node* first = newNode(1);
struct Node* second = newNode(2);
struct Node* third = newNode(3);
struct Node* head = first;
first->next = second;
second->next =
third; return head;
}
void printList(struct Node* head)
{
struct Node* ptr = head;
while (ptr)
{
printf("%d -> ", ptr->data);
ptr = ptr->next;
}
printf("NULL");
}
int main(void)
{
struct Node* head = constructList();
printList(head);
return 0;
}

SAMPLE INPUT & OUTPUT:

RESULT:
Thus the implementation of singly linked list using pointers & dynamic memory
allocation has been executed and compiled successfully.

ROLL NO: 2127220501175 PAGE NO: 11


CS22312 - DATA STRUCTURES LABORATORY
EX.NO: 3.1
DATE:

CREATION OF STACK USING ARRAY IMPLEMENTATION AND POINTER


IMPLEMENTATION
AIM:
To write a C program to implement stack using an array.

ALGORITHM:

1. Declare global variables


2. Initialize the `top` variable to -1 to indicate an empty stack.
3. Display a message to the user requesting the size of the stack (`n`).
4. Display a menu of stack operations and options to the user.
5. Enter a `do-while` loop that continues until the user chooses to exit (`choice == 4`).
6. Within the loop, prompt the user to enter their choice (`choice`).
7. Use a `switch` statement to perform actions based on the user's choice: -
Case 1: `push()`
- Case 2: `pop()`
- Case 3: `display()`
- Case 4: Exit the program.
8. Implement the `push()` function: - Check if the `top` is greater than or equal to `n-1`,
indicating a stack overflow. - If not, prompt the user to enter a value (`x`) to be
pushed onto the stack. - Increment `top` and add `x` to the `stack` at the current `top`
position.
9. Implement the `pop()` function: - Check if the `top` is less than or equal to -1,
indicating a stack underflow. - If not, display the value at the top of the stack
and decrement `top` to remove the element.
10. Implement the `display()` function:
- Check if the `top` is greater than or equal to 0, indicating that there are elements in
the stack.
- If so, display the elements in the stack from top to bottom.
- Loop through the `stack` array from `top` to 0, printing each element.
- If the stack is empty, display a message indicating that.
11. Exit the program if the user chooses option 4.
12. End the ‘main’ function.

PROGRAM:

#include<stdio.h>
int stack[100],choice,n,top,x,i;
void push(void);
void pop(void);
void display(void);
int main()
{
top=-1;
ROLL NO: 2127220501175 PAGE NO: 12
printf("\n Enter the size of STACK[MAX=100]:");
scanf("%d",&n);
printf("\n\t STACK OPERATIONS USING ARRAY");
printf("\n\t ");
printf("\n\t 1.PUSH\n\t 2.POP\n\t 3.DISPLAY\n\t 4.EXIT");
do
{
printf("\n Enter the Choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
push();
break;
}
case 2:
{
pop();
break;
}
case 3:
{
display();
break;
}
case 4:
{
printf("\n\t EXIT POINT ");
break;
}
default:
{
printf ("\n\t Please Enter a Valid Choice(1/2/3/4)");
}

}
}
while(choice!=4);
return 0;
}
void push()
{
if(top>=n-1)
{
printf("\n\tSTACK is over flow");

}
else
ROLL NO: 2127220501175 PAGE NO: 13
{
printf(" Enter a value to be pushed:");
scanf("%d",&x);
top++;
stack[top]=x;
}
}
void pop()
{
if(top<=-1)
{
printf("\n\t Stack is under flow");
}
else
{
printf("\n\t The popped elements is %d",stack[top]);
top--;
}
}
void display()
{
if(top>=0)
{
printf("\n The elements in STACK \n");
for(i=top; i>=0; i--)
printf("\n%d",stack[i]);
printf("\n Press Next Choice");
}
else
{
printf("\n The STACK is empty");
}

ROLL NO: 2127220501175 PAGE NO: 14


SAMPLE INPUT & OUTPUT:

RESULT:
Thus the creation of stack using array implementation and pointer implementation has
been executed and compiled successfully.

ROLL NO: 2127220501175 PAGE NO: 15


CS22312 - DATA STRUCTURES LABORATORY
EX.NO: 3.2
DATE:

CREATION OF STACK USING ARRAY IMPLEMENTATION AND POINTER


IMPLEMENTATION
AIM:
To write a C program to implement stack using a linked list.

ALGORITHM:

1. Include the necessary header files


2. Define a structure `struct node` to represent a node in the linked list:
- It has two members: - `info`: An integer to store the data for the node.
- `ptr`: A pointer to another `struct node`, representing the next node in the stack.
3. Declare global pointers:
- `top`: A pointer to the top of the stack.
- `top1`: A temporary pointer for various operations.
- `temp`: A temporary pointer for creating new nodes.
4. Declare global integer `count` to keep track of the number of elements in the stack.
5. Define function prototypes for stack operations:
- `int topelement()`: Get the top element of the stack without popping it.
- `void push(int data)`: Push an element onto the stack.
- `void pop()`: Pop the top element from the stack.
- `void display()`: Display the elements in the stack.
- `void stack_count()`: Count the number of elements in the stack.
- `void create()`: Initialize the stack.
6. In the `main` function:
- Declare variables `no`, `ch`, and `e`.
- Display a menu of stack operations and options to the user.
- Initialize the stack using the `create` function.
7. Enter an infinite loop to continuously perform stack operations based on user input:
- Prompt the user to enter their choice (`ch`).
- Use a `switch` statement to perform the selected stack operation.
8. Implement the `create()` function:
- Initialize the `top` pointer to `NULL`.
9. Implement the `stack_count()` function:
- Print the number of elements in the stack (`count`).
10. Implement the `push(int data)` function:
- Check if the `top` pointer is `NULL`, indicating an empty stack.
- Allocate memory for a new node and set its data and `ptr` members accordingly.
- Update the `top` pointer to point to the new node.
- Increment `count`.
11. Implement the `display()` function:
- Initialize `top1` to the `top` of the stack.
- Check if `top1` is `NULL`, indicating an empty stack.
- Iterate through the stack and print the data of each node using a loop and the `ptr`

ROLL NO: 2127220501175 PAGE NO: 16


member.
12. Implement the `pop()` function:
- Initialize `top1` to the `top` of the stack.
- Check if `top1` is `NULL`, indicating an empty stack.
- Update `top1` to point to the next node.
- Print the popped element's value.
- Free the memory of the original top node.
- Update the `top` pointer to point to the new top node.
- Decrement `count`.
13. Implement the `topelement()` function:
- Return the data value of the top node without removing it.
14. Exit the program if the user chooses option 4.
15. End the `main` function.

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 display();
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 - Exit"); printf("\
n 5 - Dipslay"); printf("\n 6 -
Stack Count"); create();
while (1)
{
printf("\n Enter choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("Enter data : ");
scanf("%d", &no);

ROLL NO: 2127220501175 PAGE NO: 17


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:
exit(0);
case 5:
display();
break;
case 6:
stack_count();
break;
default :
printf(" Wrong choice, Please enter correct choice ");
break;
}
}
}
void create()
{
top = NULL;
}
void stack_count()
{
printf("\n No. of elements in stack : %d", count);
}
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;
ROLL NO: 2127220501175 PAGE NO: 18
top = temp;
}
count++;
}
void display()
{
top1 = top;

if (top1 == NULL)
{
printf("Stack is empty");
return;
}
while (top1 != NULL)
{
printf("%d ", top1->info);
top1 = top1->ptr;
}
}
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--;
}
int topelement()
{
return(top->info);
}

ROLL NO: 2127220501175 PAGE NO: 19


SAMPLE INPUT & OUTPUT:

RESULT:
Thus the creation of stack using array implementation and pointer implementation has
been executed and compiled successfully.

ROLL NO: 2127220501175 PAGE NO: 20


CS22312 - DATA STRUCTURES LABORATORY
EX.NO: 4
DATE:

APPLICATION OF STACK: CONVERSION OF INFIX EXPRESSION INTO


POSTFIX NOTATION USING STACK

AIM:
To write a C program to convert the given Infix expression to Postfix.

ALGORITHM:

1. Include the necessary header files


2. Declare a character array `stack` to simulate a stack and initialize `top` to -1.
3. Define the `push(char x)` function to push a character onto the stack:
- Increment `top` by 1.
- Store the character `x` in the stack at the updated `top` position.
4. Define the `pop()` function to pop a character from the stack:
- Check if `top` is -1, indicating an empty stack.
- If not, return the character at the current `top` position and decrement `top`.
5. Define the `priority(char x)` function to determine the priority of operators:
- If `x` is an opening parenthesis '(', return 0 (lowest priority).
- If `x` is an addition or subtraction operator '+', '-', return 1.
- If `x` is a multiplication or division operator '*', '/', return 2.
- For other characters, return 0 (lowest priority).
6. In the `main` function:
- Declare a character array `exp` to store the input infix expression.
- Declare character pointers `e` and `x`.
- Prompt the user to enter an infix expression and store it in the `exp` array.
7. Initialize the pointer `e` to point to the beginning of the `exp` array.
8. Process the infix expression character by character using a `while` loop until the end
of the string is reached (`*e != '\0'`):
- If the current character `*e` is an alphanumeric character (operand), print it directly.
- If the current character is an opening parenthesis '(', push it onto the stack.
- If the current character is a closing parenthesis ')', pop and print characters from the
stack until an opening parenthesis '(' is encountered.
- For other operators (+, -, *, /), compare their priority with the priority of the
operator at the top of the stack:
- While the priority of the operator at the top of the stack is greater than or equal to
the current operator's priority, pop and print the top operator.
- Then, push the current operator onto the stack.
9. Increment the `e` pointer to process the next character in the infix expression.
10. After processing the entire infix expression, pop and print any remaining operators
from the stack.
11. End the `main` function.

ROLL NO: 2127220501175 PAGE NO: 21


PROGRAM:

#include<stdio.h>
#include<ctype.h>
char stack[100];
int top = -1;
void push(char x)
{
stack[++top] = x;
}
char pop()
{
if(top == -1)
return -1;
else
return stack[top--];
}
int priority(char x)
{
if(x == '(')
return 0;
if(x == '+' || x == '-')
return 1;
if(x == '*' || x == '/')
return 2;
return 0;
}
int main()
{
char exp[100];
char *e, x;
printf("Enter the expression : ");
scanf("%s",exp);
printf("\n");
e = exp;
while(*e != '\0')
{
if(isalnum(*e))
printf("%c ",*e);
else if(*e == '(')
push(*e);
else if(*e == ')')
{
while((x = pop()) != '(')
printf("%c ", x);
}
else
{
while(priority(stack[top]) >= priority(*e))

ROLL NO: 2127220501175 PAGE NO: 22


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

SAMPLE INPUT & OUTPUT:

RESULT:
Thus the convert the given Infix expression to Postfix has been executed and compiled
successfully.

ROLL NO: 2127220501175 PAGE NO: 23


CS22312 - DATA STRUCTURES LABORATORY
EX.NO: 5
DATE:

CREATION OF QUEUE USING ARRAY IMPLEMENTATION

AIM:
To write a C program to implement the queues using arrays.

ALGORITHM:

1. Include the necessary header file


2. Define a constant `n` with a value of 5 to specify the size of the queue.
3. Declare integer variables:
- `queue[n]`: An integer array to represent the queue.
- `ch`: A variable to store the user's choice for queue operations.
- `front`: An integer variable to represent the front of the queue.
- `rear`: An integer variable to represent the rear of the queue.
- `i`, `j`, `x`: Integer variables used for iteration and maintaining the count of elements
in the queue.
4. Print a menu of queue operations for the user to choose from:
- 1: Insertion
- 2: Deletion
- 3: Display
- 4: Exit
5. Enter a loop (`while(ch)`) that continues until the user chooses to exit (`ch == 4`).
6. Inside the loop, prompt the user to enter their choice (`ch`).
7. Use a `switch` statement to perform the selected queue operation:
- Case 1: Insertion
- Check if `rear` has reached the maximum capacity (`rear == x`).
- If the queue is not full, prompt the user to enter a number, and add it to the queue at
the `rear` position.
- Increment `rear` and `j` (count of elements in the queue).
- Case 2: Deletion
- Check if the queue is empty (`front == rear`).
- If not empty, remove the element from the front of the queue, print it, and increment
`front`.
- Decrement `x` (available capacity in the queue).
- Case 3: Display
- Print the elements of the queue.
- Check if the queue is empty (`front == rear`) and print a message accordingly.
- Case 4: Exit
- Terminate the program using the `exit(0)` function.
- Default: Print a message for an invalid choice.
8. End the `while` loop.
9. End the `main` function.

ROLL NO: 2127220501175 PAGE NO: 24


PROGRAM:
#include<stdio.h>
#define n 5
int main()
{
int queue[n],ch=1,front=0,rear=0,i,j=1,x=n;
printf("Queue using Array");
printf("\n1.Insertion \n2.Deletion \n3.Display \n4.Exit");
while(ch)
{
printf("\nEnter the Choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
if(rear==x)
printf("\n Queue is Full");
else
{
printf("\n Enter no %d:",j++);
scanf("%d",&queue[rear++]);
}
break;
case 2:
if(front==rear)
{
printf("\n Queue is empty");
}
else
{
printf("\n Deleted Element is %d",queue[front++]); x+
+;
}
break;
case 3:
printf("\nQueue Elements are:\n ");
if(front==rear)
printf("\n Queue is Empty");
else
{
for(i=front; i<rear; i++)
{
printf("%d",queue[i]);
printf("\n");
}
break;
case 4:
exit(0);
default:

ROLL NO: 2127220501175 PAGE NO: 25


printf("Wrong Choice: please see the options");
}
}
}
return 0;
}

SAMPLE INPUT & OUTPUT:

RESULT:
Thus the implement the queues using arrays has been executed and compiled successfully.

ROLL NO: 2127220501175 PAGE NO: 26


CS22312 - DATA STRUCTURES LABORATORY
EX.NO: 6
DATE:

CONSTRUCT A BINARY SEARCH TREE WITH TREE TRAVERSAL


TECHNIQUES – PREORDER, POST ORDER AND IN ORDER.

AIM:
To construct a Binary Search Tree with Tree traversal Techniques – Preorder, Post order
and In order.

ALGORITHM:

1. Include the necessary header files


2. Define a structure `struct TreeNode` to represent a node in the Binary Search Tree
(BST): - It contains:
- An integer `data` to store the node's value.
- Pointers `left` and `right` to represent the left and right child nodes.
3. Define a function `createNode(int data)` to create a new BST node:
- Allocate memory for a new node.
- Initialize the node's `data` to the given `data`.
- Initialize the `left` and `right` pointers to `NULL`.
- Return the newly created node.
4. Define a function `insert(struct TreeNode* root, int data)` to insert a node into the
BST:
- If `root` is `NULL`, create a new node with the given `data` and return it.
- If `data` is less than the `data` in the current `root`, recursively insert the node into
the left subtree.
- If `data` is greater than the `data` in the current `root`, recursively insert the node
into the right subtree.
- Return the modified `root`.
5. Define three tree traversal functions:
- `preorder(struct TreeNode* root)` for Preorder traversal.
- `inorder(struct TreeNode* root)` for Inorder traversal.
- `postorder(struct TreeNode* root)` for Postorder traversal.
6. In each traversal function:
- Check if `root` is `NULL`, and if so, return (base case).
- Perform the respective traversal order (Preorder: root, left, right; Inorder: left, root,
right; Postorder: left, right, root).
– Print the value of the current node.
- Recursively call the traversal function on the left and right subtrees.
7. In the `main` function:
- Declare a pointer `root` to represent the root of the BST and initialize it as `NULL`.
- Declare integer variables `choice` and `data` to manage user input.
- Enter a do-while loop that continues until the user chooses to exit (`choice == 5`).
- Display a menu of options for the user.
- Based on the user's choice, perform one of the following actions:

ROLL NO: 2127220501175 PAGE NO: 27


- Insert a node into the BST.
- Display the Preorder, Inorder, or Postorder traversal of the BST.
- Exit the program.
- After the loop, free the memory used by the BST to prevent memory leaks.
- Terminate the program.

PROGRAM:

#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int data;
struct TreeNode* left;
struct TreeNode* right;
};
struct TreeNode* createNode(int data) {
struct TreeNode* newNode = (struct TreeNode*)malloc(sizeof(struct TreeNode));
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
struct TreeNode* insert(struct TreeNode* root, int data) {
if (root == NULL) {
return createNode(data);
}
if (data < root->data) {
root->left = insert(root->left, data);
} else if (data > root->data) {
root->right = insert(root->right, data);
}
return root;
}
void preorder(struct TreeNode* root) {
if (root == NULL) {
return;
}
printf("%d ", root->data);
preorder(root->left);
preorder(root->right);
}
void inorder(struct TreeNode* root) {
if (root == NULL) {
return;
}
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
void postorder(struct TreeNode* root) {
ROLL NO: 2127220501175 PAGE NO: 28
if (root == NULL) {
return;
}
postorder(root->left);
postorder(root->right);
printf("%d ", root->data);
}
int main() {
struct TreeNode* root = NULL;
int choice, data;
do {
printf("\nBinary Search Tree Operations:\n");
printf("1. Insert a node\n");
printf("2. Preorder traversal\n");
printf("3. Inorder traversal\n");
printf("4. Postorder traversal\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter data to insert: ");
scanf("%d", &data);
root = insert(root, data);
break;
case 2:
printf("Preorder traversal: ");
preorder(root);
printf("\n");
break;
case 3:
printf("Inorder traversal: ");
inorder(root);
printf("\n");
break;
case 4:
printf("Postorder traversal: ");
postorder(root);
printf("\n");
break;
case 5:
printf("Exiting the program.\n");
break;
default:
printf("Invalid choice. Please try again.\n");
}
} while (choice != 5);
free(root);
return 0;

ROLL NO: 2127220501175 PAGE NO: 29


}

SAMPLE INPUT AND OUTPUT:

RESULT:
Thus the construct a Binary Search Tree with Tree traversal Techniques – Preorder, Post
order and In order has been executed and compiled successfully.

ROLL NO: 2127220501175 PAGE NO: 30


CS22312 - DATA STRUCTURES LABORATORY
EX.NO: 7
DATE:

CONSTRUCT AN AVL TREES AS A BALANCED SEARCH TREE AND


PERFORM THE SINGLE ROTATION

AIM:
To construct a Construct an AVL trees as a balanced search tree and perform the Single
rotation.

ALGORITHM:

1. Define the Node structure:


2. Define utility functions:
- `max(a, b)`: A utility function to find the maximum of two integers.
- `height(N)`: A function to get the height of a node N.
- `newNode(key)`: Creates a new node with the given key, initializes its height to 1, and
returns a pointer to it.
- `rightRotate(y)`: Performs a right rotation on the given node y to balance the tree.
- `leftRotate(x)`: Performs a left rotation on the given node x to balance the tree.
- `getBalance(N)`: Calculates the balance factor for a node N, which is the height of the
left subtree minus the height of the right subtree.

3. Insertion in AVL Tree:


- `insertNode(node, key)`: Inserts a new node with the given key into the AVL tree
while maintaining balance.
- If the tree is empty (`node == NULL`), it creates a new node with the given key.
- If the key is less than the current node's key, it inserts it in the left subtree.
- If the key is greater than the current node's key, it inserts it in the right subtree.
- After insertion, it updates the height of the current node and checks for balance.
- If the balance factor is greater than 1, it performs right rotations as needed.
- If the balance factor is less than -1, it performs left rotations as needed.
- Finally, it returns the updated tree.

4. Deletion in AVL Tree:


- `deleteNode(root, key)`: Deletes the node with the given key from the AVL tree while
maintaining balance.
- It first finds and deletes the node as in a standard binary search tree deletion.
- After deletion, it updates the height of the current node and checks for balance.
- If the balance factor is greater than 1, it performs right rotations as needed.
- If the balance factor is less than -1, it performs left rotations as needed.
- It returns the updated tree.

5. Traversal and Printing:


- `printPreOrder(root)`: Prints the pre-order (root, left, right) traversal of the tree.

ROLL NO: 2127220501175 PAGE NO: 31


PROGRAM:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int key;
struct Node *left;
struct Node *right;
int height;
};
int max(int a, int b);
int height(struct Node *N) {
if (N == NULL)
return 0;
return N->height;
}
int max(int a, int b) {
return (a > b) ? a : b;
}
struct Node *newNode(int key) {
struct Node *node = (struct Node *)
malloc(sizeof(struct Node));
node->key = key;
node->left = NULL;
node->right = NULL;
node->height = 1;
return (node);
}
struct Node *rightRotate(struct Node *y) {
struct Node *x = y->left;
struct Node *T2 = x->right;
x->right = y;
y->left = T2;
y->height = max(height(y->left), height(y->right)) + 1;
x->height = max(height(x->left), height(x->right)) + 1;
return x;
}
struct Node *leftRotate(struct Node *x) {
struct Node *y = x->right;
struct Node *T2 = y->left;
y->left = x;
x->right = T2;
x->height = max(height(x->left), height(x->right)) + 1;
y->height = max(height(y->left), height(y->right)) + 1;
return y;
}
int getBalance(struct Node *N) {
if (N == NULL)
return 0;
return height(N->left) - height(N->right);

ROLL NO: 2127220501175 PAGE NO: 32


}
struct Node *insertNode(struct Node *node, int key) {
if (node == NULL)
return (newNode(key));
if (key < node->key)
node->left = insertNode(node->left, key);
else if (key > node->key)
node->right = insertNode(node->right, key);
else
return node;
node->height = 1 + max(height(node->left),
height(node->right));
int balance = getBalance(node);
if (balance > 1 && key < node->left->key)
return rightRotate(node);
if (balance < -1 && key > node->right->key)
return leftRotate(node);
if (balance > 1 && key > node->left->key) {
node->left = leftRotate(node->left);
return rightRotate(node);
}
if (balance < -1 && key < node->right->key) {
node->right = rightRotate(node->right);
return leftRotate(node);
}
return node;
}
struct Node *minValueNode(struct Node *node) {
struct Node *current = node;
while (current->left != NULL)
current = current->left;
return current;
}
struct Node *deleteNode(struct Node *root, int key) {
if (root == NULL)
return root;
if (key < root->key)
root->left = deleteNode(root->left, key);
else if (key > root->key)
root->right = deleteNode(root->right, key);
else {
if ((root->left == NULL) || (root->right == NULL)) {
struct Node *temp = root->left ? root->left : root->right;
if (temp == NULL) {
temp = root;
root = NULL;
} else
*root = *temp;
free(temp);

ROLL NO: 2127220501175 PAGE NO: 33


} else {
struct Node *temp = minValueNode(root->right);
root->key = temp->key;
root->right = deleteNode(root->right, temp->key);
}
}
if (root == NULL)
return root;
root->height = 1 + max(height(root->left),
height(root->right));
int balance = getBalance(root);
if (balance > 1 && getBalance(root->left) >= 0)
return rightRotate(root);
if (balance > 1 && getBalance(root->left) < 0) {
root->left = leftRotate(root->left);
return rightRotate(root);
}
if (balance < -1 && getBalance(root->right) <= 0)
return leftRotate(root);
if (balance < -1 && getBalance(root->right) > 0) {
root->right = rightRotate(root->right);
return leftRotate(root);
}
return root;
}
void printPreOrder(struct Node *root) {
if (root != NULL) {
printf("%d ", root->key);
printPreOrder(root->left);
printPreOrder(root->right);
}
}
int main() {
struct Node *root = NULL;
root = insertNode(root, 2);
root = insertNode(root, 1);
root = insertNode(root, 7);
root = insertNode(root, 4);
root = insertNode(root, 5);
root = insertNode(root, 3);
root = insertNode(root, 8);
printPreOrder(root);
root = deleteNode(root, 3);
printf("\nAfter deletion:
"); printPreOrder(root);
return 0;
}

ROLL NO: 2127220501175 PAGE NO: 34


SAMPLE INPUT & OUTPUT:

RESULT:
Thus the construction of an avl trees as a balanced search tree and perform the single
rotation has been executed and compiled successfully.

ROLL NO: 2127220501175 PAGE NO: 35


CS22312 - DATA STRUCTURES LABORATORY
EX.NO: 8.1
DATE:

GRAPH TRAVERSAL ALGORITHM - BREADTH-FIRST SEARCH

AIM:
To perform Breadth First Search algorithm in graph data structure.

ALGORITHM:
1. Define a `Graph` structure

2. Define functions to create and destroy the graph:


- `Graph_create(int V)`: Creates a new graph with `V` vertices and initializes the
adjacency matrix with all values set to `false`.
- `Graph_destroy(Graph* g)`: Frees the memory allocated for the graph.

3. Define a function to add an edge between two vertices:


- `Graph_addEdge(Graph* g, int v, int w)`: Sets the entry in the adjacency matrix at
row `v` and column `w` to `true`, indicating an edge between vertex `v` and vertex `w`.

4. Define the Breadth-First Search (BFS) function:


- `Graph_BFS(Graph* g, int s)`: Performs BFS traversal starting from vertex `s`.
- It initializes an array `visited` to keep track of visited vertices and a queue `queue` to
store vertices for traversal.
- The BFS traversal begins with the source vertex `s`.
- It marks `s` as visited and enqueues it in the `queue`.
- While the `queue` is not empty:
- Dequeue a vertex from the `queue` and print it.
- For each adjacent vertex that is not visited, mark it as visited and enqueue it.
- The traversal continues until the `queue` is empty, visiting all connected vertices.

5. In the `main` function:


- Create a graph with 4 vertices using `Graph_create`.
- Add edges to the graph to create the graph's structure.
- Call the `Graph_BFS` function to perform a BFS traversal starting from vertex 2.
- Destroy the graph using `Graph_destroy`.

ROLL NO: 2127220501175 PAGE NO: 36


PROGRAM:
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTICES 50
typedef struct Graph_t {
int V;
bool adj[MAX_VERTICES][MAX_VERTICES];
} Graph;
Graph* Graph_create(int V)
{
Graph* g = malloc(sizeof(Graph));
g->V = V;
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++)
{
g->adj[i][j] = false;
}
}
return g;
}
void Graph_destroy(Graph* g) { free(g); }
void Graph_addEdge(Graph* g, int v, int w)
{
g->adj[v][w] = true;
}
void Graph_BFS(Graph* g, int s)
{
bool visited[MAX_VERTICES];
for (int i = 0; i < g->V; i++) {
visited[i] = false;
}
int queue[MAX_VERTICES];
int front = 0, rear = 0;
visited[s] = true; queue[rear+
+] = s;
while (front != rear)
{ s = queue[front+
+]; printf("%d ", s);
for (int adjacent = 0; adjacent < g-
>V; adjacent++) {
if (g->adj[s][adjacent] && !visited[adjacent]) {
visited[adjacent] = true;
queue[rear++] = adjacent;
}
}
}
}
int main()

ROLL NO: 2127220501175 PAGE NO: 37


{

ROLL NO: 2127220501175 PAGE NO: 38


Graph* g = Graph_create(4);
Graph_addEdge(g, 0, 1);
Graph_addEdge(g, 0, 2);
Graph_addEdge(g, 1, 2);
Graph_addEdge(g, 2, 0);
Graph_addEdge(g, 2, 3);
Graph_addEdge(g, 3, 3);
printf("Following is Breadth First Traversal "
"(starting from vertex 2) \n");
Graph_BFS(g, 2);
Graph_destroy(g);
return 0;
}

SAMPLE INPUT & OUTPUT:

RESULT:
Thus the graph traversal algorithm - breadth-first search has been executed and compiled
successfully.

ROLL NO: 2127220501175 PAGE NO: 39


CS22312 - DATA STRUCTURES LABORATORY
EX.NO: 8.2
DATE:

GRAPH TRAVERSAL ALGORITHM - DEPTH-FIRST SEARCH

AIM:
To perform Depth First Search algorithm in graph data structure.

ALGORITHM:
1. Define a `node` structure:

2. Define a `Graph` structure:


- The `Graph` structure holds the graph's properties, including the total number of
vertices, an array to track visited vertices, and an array of adjacency lists for each
vertex.

3. Define a DFS (Depth-First Search) function:


- `DFS(struct Graph* graph, int vertex)`: Performs a depth-first traversal of the
graph starting from a given vertex.
- Mark the current vertex as visited.
- Print the current vertex.
- Iterate through the adjacent vertices in the adjacency list of the current vertex:
- If an adjacent vertex is not visited, recursively call DFS on that vertex.

4. Define functions to create a new node and create the graph:


- `createNode(int v)`: Creates a new node for the adjacency list with the given
vertex number.
- `createGraph(int vertices)`: Creates a new graph with the specified number of
vertices, initializes adjacency lists, and visited status.

5. Define a function to add an edge between two vertices:


- `addEdge(struct Graph* graph, int src, int dest)`: Adds an edge between two vertices
by creating nodes in the adjacency lists of both vertices.

6. Define a function to display the graph:


- `displayGraph(struct Graph* graph)`: Prints the adjacency list representation of the
graph, showing each vertex's neighbors.

7. In the `main` function:


- Create a graph with 8 vertices using `createGraph`.
- Add edges between vertices to establish the graph structure using `addEdge`.
- Display the adjacency list representation of the graph using `displayGraph`.
- Perform a DFS traversal of the graph starting from vertex 1 using function.

ROLL NO: 2127220501175 PAGE NO: 40


PROGRAM:

#include <stdio.h>
#include <stdlib.h>
struct node {
int vertex;
struct node* next;
};
struct node* createNode(int v);
struct Graph {
int totalVertices;
int* visited;
struct node** adjLists;
};
void DFS(struct Graph* graph, int vertex) {
struct node* adjList = graph->adjLists[vertex];
struct node* temp = adjList;
graph->visited[vertex] = 1;
printf("%d -> ", vertex);
while (temp != NULL) {
int connectedVertex = temp->vertex;
if (graph->visited[connectedVertex] == 0) {
DFS(graph, connectedVertex);
}
temp = temp->next;
}
}
struct node* createNode(int v) {
struct node* newNode = malloc(sizeof(struct node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}
struct Graph* createGraph(int vertices) {
struct Graph* graph = malloc(sizeof(struct Graph));
graph->totalVertices = vertices;
graph->adjLists = malloc(vertices * sizeof(struct node*));
graph->visited = malloc(vertices * sizeof(int));
int i;
for (i = 0; i < vertices; i++) {
graph->adjLists[i] = NULL;
graph->visited[i] = 0;
}
return graph;
}
void addEdge(struct Graph* graph, int src, int dest) {
struct node* newNode = createNode(dest);

ROLL NO: 2127220501175 PAGE NO: 41


newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;
newNode = createNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode;
}
void displayGraph(struct Graph* graph) {
int v;
for (v = 1; v < graph->totalVertices; v++) {
struct node* temp = graph->adjLists[v];
printf("\n%d => ", v);
while (temp) {
printf("%d, ", temp->vertex);
temp = temp->next;
}
printf("\n");
}
printf("\n");
}
int main() {
struct Graph* graph = createGraph(8);
addEdge(graph, 1, 5);
addEdge(graph, 1, 2);
addEdge(graph, 1, 3);
addEdge(graph, 3, 6);
addEdge(graph, 2, 7);
addEdge(graph, 2, 4);
printf("\nThe Adjacency List of the Graph is:");
displayGraph(graph);
printf("\nDFS traversal of the graph: \n");
DFS(graph, 1);
return 0;
}

SAMPLE INPUT & OUTPUT:

ROLL NO: 2127220501175 PAGE NO: 42


RESULT:
Thus the Depth First Search algorithm in graph data structure has been executed and
compiled successfully.
ROLL NO: 2127220501175 PAGE NO: 43
CS22312 - DATA STRUCTURES LABORATORY
EX.NO: 9
DATE:

PERFORM THE SINGLE SOURCE SHORTEST PATH USING DIJKSTRA’S


ALGORITHM

AIM:
To perform the single source shortest path in an undirected graph using Dijkstra’s
algorithm.

ALGORITHM:

1. Define a function `minDistance` to find the vertex with the minimum distance value
from the set of vertices not yet included in the shortest path tree (`sptSet`). It iterates
through all vertices and returns the index of the vertex with the minimum distance.

2. Define a function `printSolution` to print the computed distances from the source vertex
to all other vertices.

3. Define the main `dijkstra` function to perform Dijkstra's algorithm:


- Initialize arrays `dist` and `sptSet` to store the minimum distance from the source
vertex and whether a vertex is included in the shortest path tree, respectively.
- Initialize all distances to infinity (`INT_MAX`) and set `sptSet` to all zeros, indicating
no vertices have been included in the shortest path tree yet.
- Set the distance of the source vertex to itself to 0.
- For `V - 1` iterations (where `V` is the number of vertices), perform the following:
- Find the vertex `u` with the minimum distance value from the set of vertices not yet
included in the shortest path tree using the `minDistance` function.
- Mark vertex `u` as included in the shortest path tree.
- Update the distances of all adjacent vertices to `u` that have not been included in the
shortest path tree and have a shorter path through `u`.
- Finally, call the `printSolution` function to print the computed distances from the
source vertex to all other vertices.

4. In the `main` function:


- Define a weighted graph as a 2D array `graph` representing the edges and their weights.
- Call the `dijkstra` function with the graph and the source vertex (in this case, the source
vertex is 0).

ROLL NO: 2127220501175 PAGE NO: 44


PROGRAM:

#include <stdio.h>
#include <limits.h>
#define V 9
int minDistance(int dist[], int sptSet[]) {
int min = INT_MAX, min_index;
int v;
for (v = 0; v < V; v++)
if (sptSet[v] == 0 && dist[v] <= min)
min = dist[v], min_index = v;
return min_index;
}
void printSolution(int dist[], int n) {
printf("Vertex Distance from Source\n");
int i;
for (i = 0; i < V; i++)
printf("%d \t\t %d\n", i, dist[i]);
}
void dijkstra(int graph[V][V], int src) {
int dist[V];
int sptSet[V];
int i, count,
v;
for (i = 0; i < V; i++)
dist[i] = INT_MAX, sptSet[i] = 0;
dist[src] = 0;
for (count = 0; count < V - 1; count++) {
int u = minDistance(dist, sptSet);
sptSet[u] = 1;
for (v = 0; v < V; v++)
if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u]
+ graph[u][v] < dist[v])
dist[v] = dist[u] + graph[u][v];
}
printSolution(dist, V);
}
int main() {
int graph[V][V] = {{0, 4, 0, 0, 0, 0, 0, 8, 0},
{4, 0, 8, 0, 0, 0, 0, 11, 0},
{0, 8, 0, 7, 0, 4, 0, 0, 2},
{0, 0, 7, 0, 9, 14, 0, 0, 0},
{0, 0, 0, 9, 0, 10, 0, 0, 0},
{0, 0, 4, 0, 10, 0, 2, 0, 0},
{0, 0, 0, 14, 0, 2, 0, 1, 6},
{8, 11, 0, 0, 0, 0, 1, 0, 7},
{0, 0, 2, 0, 0, 0, 6, 7, 0}
};

ROLL NO: 2127220501175 PAGE NO: 45


dijkstra(graph, 0);

ROLL NO: 2127220501175 PAGE NO: 46


return 0;
}

SAMPLE INPUT & OUTPUT:

RESULT:
Thus the single source shortest path in an undirected graph using Dijkstra’s algorithm has
been executed and compiled successfully.

ROLL NO: 2127220501175 PAGE NO: 47


CS22312 - DATA STRUCTURES LABORATORY
EX.NO: 10
DATE:

CONSTRUCT THE MINIMUM SPANNING TREE USING KRUSKAL'S


ALGORITHM
AIM:
To Construct the Minimum Spanning Tree using Kruskal's algorithm. It is a way of
finding the most economical way to connect a set of vertices.

ALGORITHM:
1. Define a custom comparator function (`comparator`) for sorting the edges in non-
decreasing order based on their weights.

2. Define the `makeSet` function to initialize the disjoint-set data structures. It


initializes the parent and rank arrays, where each element initially represents its own
set.

3. Define the `findParent` function, which uses path compression to find the
representative (parent) of a given component in the disjoint-set data structure. It
recursively finds the parent and updates the parent of each visited node along the path
to the root for efficient future queries.

4. Define the `unionSet` function, which performs the union operation to merge two
components into a single component in the disjoint-set data structure. It takes two vertices
`u` and `v`, finds their parents, and merges them based on the rank (depth) of their
respective trees. The rank is used to optimize the union operation by attaching the tree
with the smaller rank to the tree with the larger rank.

5. Define the `kruskalAlgo` function, which finds the Minimum Spanning Tree (MST) of
the graph:
- Sort the edges in non-decreasing order based on their weights using `qsort` and the
`comparator` function.
- Initialize arrays for parent and rank for the disjoint-set data structure using `makeSet`.
- Initialize `minCost` to 0, which will store the total weight of the MST.
- Iterate through the sorted edges:
- For each edge, check if its two vertices belong to different components (sets) using
`findParent`.
- If they are not in the same component, add this edge to the MST, update the
parent and rank arrays with `unionSet`, and increment `minCost` by the weight of the
edge.
- Print the edge that is added to the MST.
- After processing all edges, the MST is constructed, and its minimum cost is calculated.
- Print the edges in the MST and the total minimum cost.

6. In the `main` function:


- Define an array `edge` to represent the edges of a graph, where each edge is defined
by the vertices it connects and its weight.
ROLL NO: 2127220501175 PAGE NO: 48
- Call the `kruskalAlgo` function with the number of vertices and the array of edges.

ROLL NO: 2127220501175 PAGE NO: 49


PROGRAM:

#include <stdio.h>
#include <stdlib.h>
int comparator(const void* p1, const void* p2)
{
const int(*x)[3] = p1;
const int(*y)[3] = p2;
return (*x)[2] - (*y)[2];
}
void makeSet(int parent[], int rank[], int n)
{
for (int i = 0; i < n; i++)
{ parent[i] = i;
rank[i] = 0;
}
}
int findParent(int parent[], int component)
{
if (parent[component] == component)
return component;
return parent[component]
= findParent(parent, parent[component]);
}
void unionSet(int u, int v, int parent[], int rank[], int n)
{
u = findParent(parent,
u); v = findParent(parent,
v); if (rank[u] < rank[v])
{
parent[u] = v;
}
else if (rank[u] > rank[v]) {
parent[v] = u;
}
else {
parent[v] = u; rank[u]+
+;
}
}
void kruskalAlgo(int n, int edge[n][3])
{
qsort(edge, n, sizeof(edge[0]), comparator);
int parent[n];
int rank[n];
makeSet(parent, rank, n);
int minCost = 0;
printf(
ROLL NO: 2127220501175 PAGE NO: 50
"Following are the edges in the constructed MST\n");

ROLL NO: 2127220501175 PAGE NO: 51


for (int i = 0; i < n; i++) {
int v1 = findParent(parent, edge[i]
[0]); int v2 = findParent(parent,
edge[i][1]); int wt = edge[i][2];
if (v1 != v2) {
unionSet(v1, v2, parent, rank,
n); minCost += wt;
printf("%d -- %d == %d\n", edge[i]
[0], edge[i][1], wt);
}
}
printf("Minimum Cost Spanning Tree: %d\n", minCost);
}
int main()
{
int edge[5][3] = { { 0, 1, 10 },
{ 0, 2, 6 },
{ 0, 3, 5 },
{ 1, 3, 15 },
{ 2, 3, 4 } };
kruskalAlgo(5, edge);
return 0;
}

SAMPLE INPUT & OUTPUT:

RESULT:
Thus the Construction of the Minimum Spanning Tree using Kruskal's algorithm. It is a
way of finding the most economical way to connect a set of vertices has been executed
and compiled successfully.

ROLL NO: 2127220501175 PAGE NO: 52


CS22312 - DATA STRUCTURES LABORATORY
EX.NO: 11.1
DATE:

IMPLEMENTATION OF SORTING – INSERTION SORT

AIM:
To write a C program to implement Insertion Sort.

ALGORITHM:
1. Define a function `display` to print the elements of an array.
- Iterate through the array and print each element.

2. Define the Insertion Sort function `insertionSort`:


- Start iterating through the array from the second element (index 1) to the last
element.
- For each element, save its value in a temporary variable (`tmp`).
- Create a variable `j` and initialize it with the current element's index minus one (i.e.,
the previous element).
- While `j` is greater than or equal to 0 and the temporary value `tmp` is less than
the value at index `j`:
- Move the value at index `j` one position to the right (`arr[j] = arr[j - 1]`).
- Decrement `j`.
- Once the correct position for the `tmp` value is found (when `tmp` is greater than
or equal to `arr[j]`), insert `tmp` into the array at index `j + 1`.
- Repeat this process for all elements in the array, resulting in a sorted array.

3. In the `main` function:


- Define an integer array `arr` with unsorted elements.
- Calculate the number of elements in the array `n`.
- Print the elements of the array before sorting using the `display` function.
- Call the `insertionSort` function to sort the array.
- Print the elements of the array after sorting using the `display` function.

ROLL NO: 2127220501175 PAGE NO: 53


PROGRAM:

#include <stdio.h>
void display(int arr[], int n) {
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
void insertionSort(int arr[], int n) {
for (int i = 1; i < n; i++) {
int tmp = arr[i];
int j = i - 1;
while (tmp < arr[j] && j >= 0) {
arr[j + 1] = arr[j];
--j;
}
arr[j + 1] = tmp;
}
}
int main() {
int arr[] = {9, 5, 1, 4, 3};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Elements before sorting:\n");
display(arr, n);
insertionSort(arr, n);
printf("Elements after sorting:\n");
display(arr, n);
}

SAMPLE INPUT & OUTPUT:

RESULT:
Thus the implementation of sorting – insertion sort has been executed and compiled
successfully.

ROLL NO: 2127220501175 PAGE NO: 54


CS22312 - DATA STRUCTURES LABORATORY
EX.NO: 11.2
DATE:

IMPLEMENTATION OF BUBBLE SORT


AIM:
To write a C program to implement Bubble Sort.

ALGORITHM:

1. Define the Bubble Sort function `bubbleSort`:


- The outer loop (`step`) iterates from 0 to `size - 2` (size minus one) times.
- The inner loop (`i`) iterates from 0 to `size - step - 2` (size minus one minus
the current `step`) times.
- In the inner loop, compare each adjacent pair of elements in the array (`array[i]` and
`array[i + 1]`).
- If the element at index `i` is greater than the element at index `i + 1`, swap
the elements.
- Continue this process until the largest element "bubbles up" to the end of the array
during each pass through the inner loop.
- After each pass of the inner loop, the largest unsorted element is moved to its correct
position in the sorted part of the array.

2. Define the `printArray` function to print the elements of the array.

3. In the `main` function:


- Define an integer array `data` with unsorted elements.
- Calculate the number of elements in the array `size`.
- Call the `bubbleSort` function to sort the array in ascending order.
- Print the elements of the sorted array using the `printArray` function.

ROLL NO: 2127220501175 PAGE NO: 55


PROGRAM:

#include <stdio.h>
void bubbleSort(int array[], int size) {
for (int step = 0; step < size - 1; ++step)
{ for (int i = 0; i < size - step - 1; ++i) {
if (array[i] > array[i + 1]) {
int temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
}
}
}
}
void printArray(int array[], int size) {
for (int i = 0; i < size; ++i) {
printf("%d ", array[i]);
}
printf("\n");
}
int main() {
int data[] = {-2, 45, 0, 11, -9};
int size = sizeof(data) / sizeof(data[0]);
bubbleSort(data, size);
printf("Sorted Array in Ascending Order:\n");
printArray(data, size);
}

SAMPLE INPUT & OUTPUT:

RESULT:
Thus the implementation of bubble sort has been executed and compiled successfully.

ROLL NO: 2127220501175 PAGE NO: 56


CS22312 - DATA STRUCTURES LABORATORY
EX.NO: 11.3
DATE:

IMPLEMENTATION OF QUICK SORT

AIM:
To write a C program to implement Quick Sort.
ALGORITHM:

1. Define a `swap` function to swap two integers.


2. Define a `partition` function to select a pivot element and rearrange the elements
in the array such that elements smaller than the pivot are on the left, and elements greater
than the pivot are on the right.
- Choose the pivot element; in this implementation, the pivot is the last element of
the array (`array[high]`).
- Initialize an index `i` to `low - 1` (before the first element of the array).
- Iterate through the array from `low` to `high-1`:
- If the current element is less than or equal to the pivot, increment `i` and swap
`array[i]` with the current element, effectively moving smaller elements to the left of the
pivot.
- Swap `array[i + 1]` (the element immediately to the right of `i`) with the pivot
element, effectively placing the pivot in its correct sorted position.
- Return the index of the pivot element (`i + 1`).
3. Define the `quickSort` function to sort the array using the Quick Sort algorithm:
- If `low` is less than `high`, it means there are more than one element in the subarray.
- Call the `partition` function to find the pivot element's index (`pi`).
- Recursively call `quickSort` on the left subarray (from `low` to `pi - 1`) and the right
subarray (from `pi + 1` to `high`).
4. Define a `printArray` function to print the elements of the array.
5. In the `main` function:
- Define an integer array `data` with unsorted elements.
- Calculate the number of elements in the array `n`.
- Print the unsorted array using the `printArray` function.
- Call the `quickSort` function to sort the array in ascending order.
- Print the sorted array using the `printArray` function.

ROLL NO: 2127220501175 PAGE NO: 57


PROGRAM:

#include <stdio.h>
void swap(int *a, int *b) {
int t = *a;
*a = *b;
*b = t;
}
int partition(int array[], int low, int high) {
int pivot = array[high];
int i = (low - 1);
for (int j = low; j < high; j++)
{ if (array[j] <= pivot) {
i++;
swap(&array[i], &array[j]);
}
}
swap(&array[i + 1], &array[high]);
return (i + 1);
}
void quickSort(int array[], int low, int high) {
if (low < high) {
int pi = partition(array, low, high);
quickSort(array, low, pi - 1);
quickSort(array, pi + 1, high);
}
}
void printArray(int array[], int size) {
for (int i = 0; i < size; ++i) {
printf("%d ", array[i]);
}
printf("\n");
}
int main() {
int data[] = {8, 7, 2, 1, 0, 9, 6};
int n = sizeof(data) / sizeof(data[0]);
printf("Unsorted Array\n");
printArray(data, n);
quickSort(data, 0, n - 1);
printf("Sorted array in ascending order: \n");
printArray(data, n);
}

ROLL NO: 2127220501175 PAGE NO: 58


SAMPLE INPUT & OUTPUT:

RESULT:
Thus the implementation of quick sort has been executed and compiled successfully.

ROLL NO: 2127220501175 PAGE NO: 59


CS22312 - DATA STRUCTURES LABORATORY
EX.NO: 12.1
DATE:

HASHING IMPLEMENTATION OF SEPARATE CHAINING

AIM:

To learn about hashing techniques.

ALGORITHM:

1. Define a structure called `node` to represent a node in a singly-linked list. Each node
contains an integer data value and a pointer to the next node in the list.

2. Define an array of pointers called `chain` of size `size` (set to 7 in this case) to
represent the hash table. Each element of this array is a pointer to the head of a
linked list.

3. Define an `init` function to initialize the hash table. It sets all elements in the `chain`
array to `NULL`, indicating that there are no elements in the hash table initially.

4. Define an `insert` function to insert an integer value into the hash table:

- Create a new `node` with the given value.

- Calculate the key by taking the remainder of the value divided by the size of the
hash table (`value % size`).

- If the linked list at the calculated key is empty (i.e., `chain[key]` is `NULL`), set the
new node as the head of the list.

- If the linked list at the calculated key is not empty, traverse the list to find the end,
and then append the new node to the end of the list.

5. Define a `print` function to print the contents of the hash table:

- Iterate through each element in the `chain` array (i.e., each linked list).

- For each linked list, traverse the nodes and print the data values.

- Print "NULL" to indicate the end of each linked list.

6. In the `main` function:

- Initialize the hash table using the `init` function.

Insert several values (e.g., 15, 11, 27, 8) into the hash table using the `insert` function.

ROLL NO: 2127220501175 PAGE NO: 60


PROGRAM:

#include<stdio.h>

#include<stdlib.h>

#define size 7

struct node

int data;

struct node *next;

};

struct node *chain[size];

void init()

int i;

for(i = 0; i < size; i++)

chain[i] = NULL;

void insert(int value)

struct node *newNode = malloc(sizeof(struct node));

newNode->data = value;

newNode->next = NULL;

int key = value % size;

if(chain[key] == NULL)

chain[key] = newNode;

else

struct node *temp = chain[key];

ROLL NO: 2127220501175 PAGE NO: 61


while(temp->next)

temp = temp->next;

temp->next = newNode;

void print()

int i;

for(i = 0; i < size; i++)

struct node *temp = chain[i];

printf("chain[%d]-->",i);

while(temp)

printf("%d -->",temp->data);

temp = temp->next;

printf("NULL\n");

int main()

init();

insert(15);

insert(11);

ROLL NO: 2127220501175 PAGE NO: 62


insert(27);

insert(8);

print();

return 0;

SAMPLE INPUT & OUTPUT:

RESULT:

Thus the hashing implementation of separate chaining has been executed and compiled
successfully.

ROLL NO: 2127220501175 PAGE NO: 63


CS22312 - DATA STRUCTURES LABORATORY
EX.NO: 12.2
DATE:

HASHING IMPLEMENTATION OF OPEN ADDRESSING


(Linear Probing)

AIM:
To write a C program for Linear probing techniques.

ALGORITHM:
1. Define an array `h` of size `TABLE_SIZE` (set to 10 in this case) to represent the
hash table. Each element of this array will store an integer value or be initialized to
`NULL`.

2. Define a function `insert` to insert an integer value into the hash table:
- Prompt the user to enter a value to insert.
- Calculate the hash key by taking the remainder of the value divided by the size of the
hash table (`key % TABLE_SIZE`).
- Use linear probing to find the appropriate index for insertion:
- Start with the calculated hash key (`hkey`) and check the element at that index.
- If the element is `NULL`, insert the value at that index and break.
- If the element is not `NULL`, increment the index (`hkey + 1`) and check the next
index.
- Continue this process until an empty slot is found or until the entire hash table is
checked.
- If the loop finishes without finding an empty slot, print a message indicating that the
element cannot be inserted.

3. Define a function `search` to search for a value in the hash table:


- Prompt the user to enter a value to search for.
- Calculate the hash key by taking the remainder of the value divided by the size of the
hash table (`key % TABLE_SIZE`).
- Use linear probing to search for the value:
- Start with the calculated hash key (`hkey`) and check the element at that index.
- If the element matches the value being searched for, print the index where it was
found.
- If the element is not the target value, increment the index (`hkey + 1`) and check
the next index.
- Continue this process until the target value is found or until the entire hash table is
checked.
- If the loop finishes without finding the target value, print a message indicating that
the value is not found.

ROLL NO: 2127220501175 PAGE NO: 64


4. Define a function `display` to print the contents of the hash table.

5. In the `main` function:


- Display a menu for the user with options to insert, display, search, or exit.
- Depending on the user's choice, call the corresponding function (`insert`, `display`,
`search`, or `exit`).

PROGRAM:

#include <stdio.h>
#include<stdlib.h>
#define TABLE_SIZE 10
int h[TABLE_SIZE]={NULL};
void insert()
{
int key,index,i,flag=0,hkey;
printf("\nenter a value to insert into hash table\n");
scanf("%d",&key);
hkey=key%TABLE_SIZE;
for(i=0;i<TABLE_SIZE;i++)
{
index=(hkey+i)%TABLE_SIZE;
if(h[index] == NULL)
{
h[index]=key;
break;
}
}
if(i == TABLE_SIZE)
printf("\nelement cannot be inserted\n");
}
void search()
{
int key,index,i,flag=0,hkey; printf("\
nenter search element\n");
scanf("%d",&key); hkey=key
%TABLE_SIZE;
for(i=0;i<TABLE_SIZE; i++)
{
index=(hkey+i)%TABLE_SIZE;
if(h[index]==key)
{
printf("value is found at index %d",index);
break;
}
}
if(i == TABLE_SIZE)
ROLL NO: 2127220501175 PAGE NO: 65
printf("\n value is not found\n");
}
void display()
{
int i;
printf("\nelements in the hash table are \n");
for(i=0;i< TABLE_SIZE; i++)
printf("\nat index %d \t value = %d",i,h[i]);
}
main()
{
int opt,i;
while(1)
{
printf("\nPress 1. Insert\t 2. Display \t3. Search \t4.Exit \n");
scanf("%d",&opt);
switch(opt)
{
case 1:
insert();
break;
case 2:
display();
break;
case 3:
search();
break;
case 4:exit(0);
}
}
}

ROLL NO: 2127220501175 PAGE NO: 66


SAMPLE INPUT & OUTPUT:

RESULT:
Thus the hashing implementation of open addressing (linear probing) has been executed
and compiled successfully.

ROLL NO: 2127220501175 PAGE NO: 67

You might also like