Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
5 views63 pages

Data Structures

The document outlines various C programs for implementing data structures such as Stack, Queue, List, and Singly Linked List using arrays and linked lists. Each section includes the aim, algorithm, program code, and sample output for the respective data structure operations. The programs demonstrate fundamental operations like insertion, deletion, and display of elements.
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)
5 views63 pages

Data Structures

The document outlines various C programs for implementing data structures such as Stack, Queue, List, and Singly Linked List using arrays and linked lists. Each section includes the aim, algorithm, program code, and sample output for the respective data structure operations. The programs demonstrate fundamental operations like insertion, deletion, and display of elements.
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/ 63

CS1307 – Data Structures Lab 2024-2025 Department of IT

Ex No:1.a Array implementation of Stack ADTs


Date:
Aim:
To write a C program to implement Stack ADT using Array.
Algorithm:
1. Define a class Stack with an integer array data member to store the elements of the stack,
with member functions to perform all the operations of the stack
1. Initialize top index as ‘0’ to indicate stack empty.
2. Push has an argument for the element to be pushed into the stack, check for stack full
condition, else increment top index and place the element in the stack.
3. Pop function checks for stack empty, else sets the top index element to ‘0’ and
decrements the top index.
4. Display function, checks for stack empty, else displays all the elements of the stack from
top index to first index.
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;
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(){

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
if(top>=n-1) {
printf("\n\tSTACK is over flow");}
else{
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"); } }
Output:
Enter the size of STACK[MAX=100]:10
STACK OPERATIONS USING ARRAY
--------------------------------
1.PUSH 2.POP 3.DISPLAY 4.EXIT
Enter the Choice: 1
Enter a value to be pushed: 12
Enter the Choice: 1
Enter a value to be pushed: 24
Enter the Choice: 1
Enter a value to be pushed: 98
Enter the Choice: 3
The elements in STACK
98
24
12
Press Next Choice
Enter the Choice: 2 The popped elements is 98
Enter the Choice: 3 The elements in STACK
4
12
Press Next Choice
Enter the Choice: 4
EXIT POINT

Result:

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT

Ex No: 1.b Array implementation of QUEUE ADTs


Date:
Aim:
To write a ‘C’ program to implement Queue using Array.
Algorithm:
1. Define a class with an array data member for the elements of the queue.
1. Initialize the front and rear indices to ‘0’.
2. If the queue is empty, the function enqueue insets a new element in the queue and
increments both front and rear index values . Else the element is inserted by
incrementing the rear index value and inserting the element at that position.
3. The dequeue function deletes the front element and assigns the next element as the
front element.
4. Appropriate function invocations are done and the results are displayed.
Program:
#include <stdio.h>
#define MAX 50
int queue_array[MAX];
int rear = - 1;
int front = - 1;
main(){
int choice;
while (1){
printf("1.Insert element to queue \n");
printf("2.Delete element from queue \n");
printf("3.Display all elements of queue \n");
printf("4.Quit \n");
printf("Enter your choice : ");
scanf("%d", &choice);
switch (choice){
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
display();
break;
case 4:
exit(1);
default:
printf("Wrong choice \n"); } /*End of switch*/ } /*End of while*} /*End of main()*/
insert(){
int add_item;
if (rear == MAX - 1)
printf("Queue Overflow \n");
else{

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
if (front == - 1) /*If queue is initially empty */
front = 0;
printf("Inset the element in queue : ");
scanf("%d", &add_item);
rear = rear + 1;
queue_array[rear] = add_item; }} /*End of insert()*/

delete(){
if (front == - 1 || front > rear){
printf("Queue Underflow \n");
return ;}
else {
printf("Element deleted from queue is : %d\n", queue_array[front]);
front = front + 1; }} /*End of delete() */
display(){ int i;
if (front == - 1)
printf("Queue is empty \n");
else{ printf("Queue is : \n");
for (i = front; i <= rear; i++)
printf("%d ", queue_array[i]);
printf("\n");}}
Output:
1.Insert element to queue
2.Delete element from queue
3.Display all elements of queue
4.Quit
Enter your choice : 1
Inset the element in queue : 10
1.Insert element to queue
2.Delete element from queue
3.Display all elements of queue
4.Quit
Enter your choice : 1
Inset the element in queue : 15
1.Insert element to queue
2.Delete element from queue
3.Display all elements of queue
4.Quit
Enter your choice : 2
Element deleted from queue is : 10
1.Insert element to queue
2.Delete element from queue
3.Display all elements of queue
4.Quit
Enter your choice : 3
Queue is : 15
Result:

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
Ex.No:2 Implementation of List ADT
Date:
Aim
To write a ‘c’ program to implement list ADT.
Algorithm
Step 1:- Define a array as a node of a structure with elements.
Step 2:- Declare the function prototypes create( ),insert( ),delete( ) and display( ) to perform the
array operations.
Step 3:- Get a choice from the user. If the choice is create, get first data from the user by calling
the function create( ), assign the new node as fist and last, and display contents of the list.
Step 4:- If the choice is insert, get the data by calling the function insert(). Display the contents of
the array.
Step 5:- If the choice is delete, remove the data from the array.
Step 6: :- If the choice is search(), to search the data in the array.
Step 7:- Repeat the steps 4, 5 & 6 until the choice is exit.
Step 8:- Terminate the execution.
Program:
#include<stdio.h>
#include<stdlib.h>
#define MAX 10
void create();
void insert();
void deletion();
void search();
void display();
int a,b[20], n, p, e, f, i, pos;
void main(){
int ch;
char g='y';
do{
printf("\n main Menu");
printf("\n 1.Create \n 2.Delete \n 3.Search \n 4.Insert \n 5.Display\n 6.Exit \n");
printf("\n Enter your Choice");
scanf("%d", &ch);
switch(ch){
case 1:
create();
break;
case 2:
deletion();
break;
case 3:
search();
break;
case 4:
insert();
break;
case 5:

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
display();
break;
case 6:
exit(0);
break;
default:
printf("\n Enter the correct choice:");}
printf("\n Do u want to continue:::");
scanf("\n%c", &g);}
while(g=='y'||g=='Y');}
void create(){
printf("\n Enter the number of nodes");
scanf("%d", &n);
for(i=0;i<n;i++){
printf("\n Enter the Element:",i+1);
scanf("%d", &b[i]);}}
void deletion(){
printf("\n Enter the position u want to delete::");
scanf("%d", &pos);
if(pos>=n){
printf("\n Invalid Location::");}
else{
for(i=pos+1;i<n;i++){
b[i-1]=b[i];}
n--;}
printf("\n The Elements after deletion");
for(i=0;i<n;i++){
printf("\t%d", b[i]);}}
void search(){
int flag=0;
printf("\n Enter the Element to be searched:");
scanf("%d", &e);
for(i=0;i<=n;i++){
if(b[i]==e){
flag=1;
printf("Value is in the %d Position", i);}}
if(flag==0){
printf("Value %d is not in the list::", e);}}
void insert(){
printf("\n Enter the position u need to insert::");
scanf("%d", &pos);
if(pos>=n){
printf("\n invalid Location::"); }
else{
for(i=MAX-1;i>=pos-1;i--){
b[i+1]=b[i];}
printf("\n Enter the element to insert::\n");
scanf("%d",&p);

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
b[pos]=p;
n++;}
printf("\n The list after insertion::\n");
display();}
void display(){
printf("\n The Elements of The list ADT are:");
for(i=0;i<n;i++){
printf("\n\n%d", b[i]);}}
Output:
main Menu
1.Create 2.Delete 3.Search 4.Insert 5.Display6.Exit
Enter your Choice1 Enter the number of nodes3
Enter the Element:10
Enter the Element:20
Enter the Element:30
Do u want to continue:::y main Menu1.Create 2.Delete 3.Search 4.Insert 5.Display6.Exit
Enter your Choice2
Enter the position u want to delete::4
Invalid Location::
The Elements after deletion 10 20 30
Do u want to continue:::y main Menu1.Create 2.Delete 3.Search 4.Insert 5.Display 6.Exit
Enter your Choice3
Enter the Element to be searched:20
Value is in the 1 Position
Do u want to continue:::y
main Menu
1.Create 2.Delete 3.Search 4.Insert 5.Display6.Exit
Enter your Choice4
Enter the position u need to insert::3
invalid Location::
The list after insertion::
The Elements of The list ADT are:
10 20 30
Do u want to continue:::y main Menu1.Create 2.Delete 3.Search 4.Insert 5.Display 6.Exit
Enter your Choice4
Enter the position u need to insert::2
Enter the element to insert::
30
The list after insertion::
The Elements of The list ADT are:
10 20 30 30
Do u want to continue:::y main Menu1.Create 2.Delete 3.Search 4.Insert 5.Display 6.Exit
Enter your Choice5
The Elements of The list ADT are:
10 20 30 30
Result:

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT

Ex.No:3.A Implementation of Singly Linked List


Date:
Aim
To write a ‘c’ program to implement single linked list.
Algorithm
Step 1:- Define a list as a node of a structure.
Step 2:- Declare the function prototypes insert ( ), delete ( ), search () and display ( ) to perform
the list functions.
Step 3:- Declare necessary pointer variables as struct node data type and initialize first and last as
NULL.
Step 4:- If the choice is insert, get the data by calling the function beginsert (), lastinsert (),
randominsert().
Step 5:- If the choice is delete, get the data by calling the function begin_delete(), last_delete(),
random_delete().
Step 6: If the choice is display (), display the list.
Step 7: If the choice is search (), it searches the element in the list.
Step 8:- Repeat the steps 4, 5, 6 & 7 until the choice is exit.
Step 9:- Terminate the execution.
Program
#include<stdio.h>
#include<stdlib.h>
struct node {
int data;
struct node *next; };
struct node *head;
void beginsert ();
void lastinsert ();
void randominsert();
void begin_delete();
void last_delete();
void random_delete();
void display();
void search();
void main () {
int choice =0;
while(choice != 9) {
printf("\n\n*********Main Menu*********\n");
printf("\nChoose one option from the following list ...\n");
printf("\nEnter your choice?\n");
scanf("\n%d",&choice);
switch(choice) {
case 1:
beginsert();
break;
case 2:
lastinsert();

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
break;
case 3:
randominsert();
break;
case 4:
begin_delete();
break;
case 5:
last_delete();
break;
case 6:
random_delete();
break;
case 7:
search();
break;
case 8:
display();
break;
case 9:
exit(0);
break;
default:
printf("Please enter valid choice.."); } } }
void beginsert() {
struct node *ptr;
int item;
ptr = (struct node *) malloc(sizeof(struct node *));
if(ptr == NULL) {
printf("\nOVERFLOW"); }
else {
printf("\nEnter value\n");
scanf("%d",&item);
ptr->data = item;
ptr->next = head;
head = ptr;
printf("\nNode inserted"); } }
void lastinsert() {
struct node *ptr,*temp;
int item;
ptr = (struct node*)malloc(sizeof(struct node));
if(ptr == NULL) {
printf("\nOVERFLOW"); }
else {
printf("\nEnter value?\n");
scanf("%d",&item);
ptr->data = item;
if(head == NULL) { ptr -> next = NULL; head = ptr; printf("\nNode inserted"); }

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
else { temp = head; while (temp -> next != NULL) {
temp = temp -> next; }
temp->next = ptr;
ptr->next = NULL;
printf("\nNode inserted"); } } }
void randominsert() {
int i,loc,item;
struct node *ptr, *temp;
ptr = (struct node *) malloc (sizeof(struct node));
if(ptr == NULL) {
printf("\nOVERFLOW"); }
else {
printf("\nEnter element value");
scanf("%d",&item);
ptr->data = item;
printf("\nEnter the location after which you want to insert ");
scanf("\n%d",&loc);
temp=head;
for(i=0;i<loc;i++) {
temp = temp->next;
if(temp == NULL) {
printf("\ncan't insert\n");
return; } }
ptr ->next = temp ->next;
temp ->next = ptr;
printf("\nNode inserted"); } }
void begin_delete() {
struct node *ptr;
if(head == NULL) {
printf("\nList is empty\n"); }
else {
ptr = head;
head = ptr->next;
free(ptr);
printf("\nNode deleted from the begining ...\n"); } }
void last_delete() {
struct node *ptr,*ptr1;
if(head == NULL) {
printf("\nlist is empty"); }
else if(head -> next == NULL) {
head = NULL;
free(head);
printf("\nOnly node of the list deleted ...\n"); }
else {
ptr = head;
while(ptr->next != NULL) {
ptr1 = ptr;
ptr = ptr ->next; }

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
ptr1->next = NULL;
free(ptr);
printf("\nDeleted Node from the last ...\n"); } }
void random_delete() {
struct node *ptr,*ptr1;
int loc,i;
printf("\n Enter the location of the node after which you want to perform deletion \n");
scanf("%d",&loc);
ptr=head;
for(i=0;i<loc;i++) {
ptr1 = ptr;
ptr = ptr->next;
if(ptr == NULL) {
printf("\nCan't delete");
return; } }
ptr1 ->next = ptr ->next;
free(ptr);
printf("\nDeleted node %d ",loc+1); }
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("item found at location %d ",i+1);
flag=0; }
else {
flag=1; }
i++;
ptr = ptr -> next; }
if(flag==1) {
printf("Item not found\n"); } } }
void display() {
struct node *ptr;
ptr = head;
if(ptr == NULL) {
printf("Nothing to print"); }
else {
printf("\nprinting values . . . . .\n");
while (ptr!=NULL) {
printf("\n%d",ptr->data);
ptr = ptr -> next; } } }
Output:
*********Main Menu*********
Choose one option from the following list ...
Enter your choice?1

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
Enter value10
Node inserted
*********Main Menu*********
Choose one option from the following list .
Enter your choice?2
Enter value?20
Node inserted
*********Main Menu*********
Choose one option from the following list ...
Enter your choice?3
Enter element value52
Enter the location after which you want to insert 0
Node inserted
*********Main Menu*********
Choose one option from the following list ...
Enter your choice?8
printing values . . . . .10 52 20
*********Main Menu*********
Choose one option from the following list ...
Enter your choice?4
Node deleted from the begining ...
*********Main Menu*********
Choose one option from the following list ...
Enter your choice?8
printing values . . . . .52 20
*********Main Menu*********
Choose one option from the following list ...
Enter your choice?6
Enter the location of the node after which you want to perform deletion 1
Deleted node 2
*********Main Menu*********
Choose one option from the following list ...
Enter your choice?8
printing values . . . . .52
*********Main Menu*********
Choose one option from the following list ...
Enter your choice?7
Enter item which you want to search?52
item found at location 1
*********Main Menu*********
Choose one option from the following list ...
Enter your choice?9
Result:

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT

Ex.No:3.b Implementation of Stack and its operations using List.


Date:
Aim
To write a ‘c’ program to implement stack ADT using Linked List.
Algorithm
Step 1:- Define a list as a node of a structure with one DATA and one LINK pointing to the next
element in the structure.
Step 2:- Declare the function prototypes create( ),insert( ),delete( ) and display( ) to perform the
list functions.
Step 3:- Declare necessary pointer variables as struct node data type and initialize first and last as
NULL..
Step 4:- Get a choice from the user. If the choice is create, get first data from the user by calling
the function create( ), assign the new node as fist and last, and display contents of the list.
Step 5:- If the choice is insert, get the data by calling the function push( ), the LINK field of the
new node points to the fist node and reassign the new node as the first node. Display the contents
of the queue.
Step 6:- If the choice is delete, remove the data from the fist of the queue.
Step 7:- Repeat the steps 4, 5 & 6 until the choice is exit.
Step 8:- Terminate the execution.
Program
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *link;};
struct node *cur,*first;
void create();
void push();
void pop();
void display();
void create(){
printf("\nENTER THE FIRST ELEMENT: ");
cur=(struct node *)malloc(sizeof(struct node));
scanf("%d",&cur->data);
cur->link=NULL;
first=cur;}
void display(){
cur=first;
printf("\n");
while(cur!=NULL){
printf("%d\n",cur->data);
cur=cur->link;}}
void push(){
printf("\nENTER THE NEXT ELEMENT: ");
cur=(struct node *)malloc(sizeof(struct node));
scanf("%d",&cur->data);
cur->link=first;

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
first=cur;}
void pop(){
if(first==NULL){
printf("\nSTACK IS EMPTY\n");}
else{
cur=first;
printf("\nDELETED ELEMENT IS %d\n",first->data);
first=first->link;
free(cur);}}
void main(){
int ch;
while(1){
printf("\n\n 1.CREATE \n 2.PUSH \n 3.POP \n 4.EXIT \n");
printf("\n ENTER YOUR CHOICE : ");
scanf("%d",&ch);
switch(ch){
case 1: create();
display();
break;
case 2: push();
display();
break;
case 3: pop();
display();
break;
case 4: exit(0);}}}

Output
1.CREATE 2.PUSH 3.POP 4.EXIT
ENTER YOUR CHOICE : 1
ENTER THE FIRST ELEMENT: 20 20
1.CREATE 2.PUSH 3.POP 4.EXIT
ENTER YOUR CHOICE : 2
ENTER THE NEXT ELEMENT: 40 40 20
1.CREATE 2.PUSH 3.POP 4.EXIT
ENTER YOUR CHOICE : 2
ENTER THE NEXT ELEMENT: 50 50 40 20
1.CREATE 2.PUSH 3.POP 4.EXIT
ENTER YOUR CHOICE : 3
DELETED ELEMENT IS 50 40 20
1.CREATE 2.PUSH 3.POP 4.EXIT
ENTER YOUR CHOICE : 4
Result:

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT

Ex No: 3.c Implementation Queue and its operations using List


Date:
Aim
To write a C program to implement queue ADT using Linked List.
Algorithm
Step 1:- Define a list as a node of a structure with one DATA and one LINK pointing to the next
element in the structure.
Step 2:- Declare the function prototypes create( ),insert( ),delete( ) and display( ) to perform the
list functions.
Step 3:- Declare necessary pointer variables as struct node data type and initialize first and last.
Step 4:- Get a choice from the user. If the choice is create, get first data from the user by calling
the function create( ), assign the new node as first and last, and display contents of the list.
Step 5:- If the choice is insert, get the data by calling the function insert( ), assign the LINK field
of the new node as NULL, LINK field of the last node points to the new node and reassign the
new node as last node. Display the contents of the queue.
Step 6:- If the choice is delete, remove the data from the fist of the queue.
Step 7:- Repeat the steps 4, 5 & 6 until the choice is exit.
Step 8:- Terminate the execution.
Program
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *link;
};struct node *cur,*first,*last;
void create();
void enqueue();
void dequeue();
void display();
void create(){
printf("\nENTER THE FIRST ELEMENT: ");
cur=(struct node *)malloc(sizeof(struct node));
scanf("%d",&cur->data);
cur->link=NULL;
first=cur;
last=cur;}
void enqueue()
{printf("\nENTER THE NEXT ELEMENT: ");
cur=(struct node *)malloc(sizeof(struct node));
scanf("%d",&cur->data);
cur->link=NULL;
last->link=cur;
last=cur;}
void dequeue()
{if(first==NULL)
{printf("\t\nQUEUE IS EMPTY\n");}
else{cur=first;

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
first=first->link;
cur->link=NULL;
printf("\n DELETED ELEMENT IS %d\n",cur->data);
free(cur);}}
void display(){cur=first;
printf("\n");
while(cur!=NULL){
printf("\t%d",cur->data);
cur=cur->link;}}
void main(){
int ch;
while(1){
printf("\n\n 1.CREATE \n 2.ENQUEUE \n 3.DEQUEUE \n 4.EXIT \n");
printf("\nENTER YOUR CHOICE : ");
scanf("%d",&ch);
switch(ch){
case 1:create();
display();
break;
case 2:enqueue();
display();
break;
case 3:dequeue();
display();
break;
case 4:exit(0);}}}
Output
1.CREATE 2.ENQUEUE 3.DEQUEUE 4.EXIT
ENTER YOUR CHOICE : 1
ENTER THE FIRST ELEMENT: 5 5
1.CREATE 2.ENQUEUE 3.DEQUEUE 4.EXIT
ENTER YOUR CHOICE : 2
ENTER THE NEXT ELEMENT: 4 5 4
1.CREATE 2.ENQUEUE 3.DEQUEUE 4.EXIT
ENTER YOUR CHOICE : 2
ENTER THE NEXT ELEMENT: 3 5 4 2
1.CREATE 2.ENQUEUE 3.DEQUEUE 4.EXIT
ENTER YOUR CHOICE : 3
DELETED ELEMENT IS 5 4 3
1.CREATE 2.ENQUEUE 3.DEQUEUE 4.EXIT
ENTER YOUR CHOICE : 4

Result:

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT

Ex.No:4.a IMPLEMENTATION OF POLYNOMIAL ADT


Date:
Aim
To implement Polynomial ADT.
Algorithm:
1. Define the structure of the node.
2. Create the first Polynomial equation by calling create function. Allocate Memory for the node
using malloc() function then assign the coefficient and power value.
3. While Poly1 and Poly2 are not null, repeat the process.
4. i) If powers of the two Polynomials are equal then add the coefficients of Poly1 and Poly2
then insert the sum of the terms into the Poly and Advance Poly1 and Poly2.
ii) Else if the power of the first polynomial> power of second Then insert the coefficient
&Power from first polynomial (Poly1) into sum polynomial (Poly) Advance Poly1.
iii) Else insert the coefficient & Power from second polynomial into sum polynomial (Poly)
Advance Poly2.
5. Copy the remaining terms from the non-empty polynomial into the sum polynomial (Poly).
6. Finally the algorithm is to be processed till the end of the polynomials has not been reached.
Program:
struct Node{
int coeff;
int pow;
struct Node *next;}; // Function to create new node
void create_node(int x, int y, struct Node **temp){
struct Node *r, *z;
z = *temp;
if(z == NULL){
r =(struct Node*)malloc(sizeof(struct Node));
r->coeff = x;
r->pow = y;
*temp = r;
r->next = (struct Node*)malloc(sizeof(struct Node));
r = r->next;
r->next = NULL;}
else{
r->coeff = x;
r->pow = y;
r->next = (struct Node*)malloc(sizeof(struct Node));
r = r->next;
r->next = NULL; }}// Function Adding two polynomial numbers
void polyadd(struct Node *poly1, struct Node *poly2, struct Node *poly){
while(poly1->next && poly2->next){
// If power of 1st polynomial is greater then 2nd, then store 1st as it is // and move its pointer
if(poly1->pow > poly2->pow){
poly->pow = poly1->pow;
poly->coeff = poly1->coeff;
poly1 = poly1->next;}// If power of 2nd polynomial is greater then 1st, then store 2nd as it is
else if(poly1->pow < poly2->pow){

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
poly->pow = poly2->pow;
poly->coeff = poly2->coeff;
poly2 = poly2->next;// If power of both polynomial numbers is same then add their coefficients
else{
poly->pow = poly1->pow;
poly->coeff = poly1->coeff+poly2->coeff;
poly1 = poly1->next;
poly2 = poly2->next;} // Dynamically create new node
poly->next = (struct Node *)malloc(sizeof(struct Node));
poly = poly->next;
poly->next = NULL;}
while(poly1->next || poly2->next){
if(poly1->next){
poly->pow = poly1->pow;
poly->coeff = poly1->coeff;
poly1 = poly1->next;} if(poly2->next){
poly->pow = poly2->pow;
poly->coeff = poly2->coeff;
poly2 = poly2->next;}
poly->next = (struct Node *)malloc(sizeof(struct Node));
poly = poly->next;
poly->next = NULL;}// Display Linked list
void show(struct Node *node){
while(node->next != NULL){
printf("%dx^%d", node->coeff, node->pow);
node = node->next;
if(node->next != NULL) printf(" + "); }} // Driver program
int main(){
struct Node *poly1 = NULL, *poly2 = NULL, *poly = NULL;
// Create first list of 5x^2 + 4x^1 + 2x^0
create_node(5,2,&poly1);
create_node(4,1,&poly1);
create_node(2,0,&poly1);// Create second list of 5x^1 + 5x^0
create_node(5,1,&poly2);
create_node(5,0,&poly2);
printf("1st Polynomial Equation: ");show(poly1);
printf("\n2nd Polynomial Equation: "); show(poly2);
poly = (struct Node *)malloc(sizeof(struct Node)); // Function add two polynomial numbers
polyadd(poly1, poly2, poly); // Display resultant List
printf("\nAdded polynomial: "); show(poly);
return 0;}
Output:
1st Polynomial Equation: 5x^2 + 4x^1 + 2x^0
2nd Polynomial Equation: 5x^1 + 5x^0
Added polynomial: 5x^2 + 9x^1 + 7x^0
Result:

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
Ex.No: 4.b Implementation of Stack operations to convert Infix to Postfix Expression
Date:
Aim
To implement stack and use it to convert infix to postfix expression.
Algorithm
Step 1:- Initialize the Stack array with maximum size.
Step 2:- Read an expression.
Step 3:- Scan the expression from left to right and repeat steps 4 to 7 for each character in the
expression till the delimiter.
Step 4:- If the character is an operand, place it on to the output.
Step 5:- If the character is an operator, then check the Stack operator has a higher or equal
priority than the input operator then pop that operator from the stack and place it onto the output.
Repeat this till there is no higher priority operator on the top of the Stack and push the input
operator onto the Stack.
Step 6:- If the character is a left parenthesis, push it onto the Stack.
Step 7:- If the character is a right parenthesis, pop all the operators from the stack till it
encounters left parenthesis. Discard both the parenthesis in the output.
Step 8:- Terminate the execution.
Program
#include<stdio.h>
//#include<process.h>
#include<stdlib.h>
#define SIZE 20
char Expr[SIZE];
char Stack[SIZE];
int Top=-1;
void push(char ch);
void pop();
void infix_to_postfix();
int m,l;
void main(){
char ch;
printf("Program to covert infix expression into postfix expression:\n");
printf("Enter your expression & to quit enter fullstop(.)\n");
while((ch=getc(stdin))!='\n'){
Expr[m]=ch;
m++;}
l=m;infix_to_postfix();}
void push(char ch){
if(Top+1 >= SIZE){
printf("\nStack is full");}
else{
Top=Top+1;
Stack[Top] = ch;}}
void pop(){
if (Top < 0){
printf("\n Stack is empty");}
else{if(Top >=0){

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
if(Stack[Top]!='(') printf("%c",Stack[Top]);
Top=Top-1;}}}
void infix_to_postfix(){
m=0;
while(m<l){
switch(Expr[m]){
case '+' :
case '-' :while(Stack[Top] =='-' || Stack[Top] =='+' ||Stack[Top] =='*'
||Stack[Top] =='/' ||Stack[Top] =='^' && Stack[Top] !='(')pop();
push(Expr[m]);++m;break;
case '/' :
case '*' :while(Stack[Top] =='*' ||Stack[Top] =='/' ||Stack[Top] =='^' &&
Stack[Top] !='(') pop();push(Expr[m]);++m;break;
case '^':push(Expr[m]);++m;break;
case '(':push(Expr[m]);++m;break;
case ')':while(Stack[Top]!='(')pop();pop();++m;break;
case '.' :while (Top >= 0)pop();exit(0);
default :if(isalpha(Expr[m])){printf("%c",Expr[m]);
++m;break;}
else{printf("\n Some error");exit(0);}}}}
Output
Program to covert infix expression into postfix expression:
Enter your expression & to quit enter fullstop(.)
A+B
AB+

Result:

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
Ex.No: 4.c Implementation of Stack operations for Evaluating Postfix Expression
Date:
Aim
To write a C program to evaluate a postfix expression using Stack.
Algorithm
Step 1:- Make an empty Stack.
Step 2:- Read an expression.
Step 3:- Scan the expression from left to right and repeat steps 2 & 3 for each element in the
expression.
Step 4:- If an operand is encountered, push it on to the stack.
Step 5:- If an operator is encounters, then
a) Remove the two top elements from the stack.
b) Perform the required operation.
c) Place the result back on to the stack.
Step 6:- Set ‘value’ equal to the top most element on stack.
Step 7:- Terminate the execution.
Program
#include<stdio.h>
#include<string.h>
#include<ctype.h>
int pop();
int i,l,top=-1,value[25],val,p,q,r;
char a[25],x;
void main(){
printf("\nEnter the postfix expression\n");
gets(a);
l=strlen(a);
for(i=0;i<l;i++){if(isalpha(a[i])){
printf("\nEnter the value for %c",a[i]);
scanf("%d",&val);top=top+1;value[top]=val;}
else{x=a[i];p=pop();q=pop();
switch(x){
case '+': r=p+q;top=top+1;value[top]=r; break;
case '-': r=q-p;top=top+1;value[top]=r;break;
case '*': r=p*q;top=top+1;value[top]=r; break;
case '/': r=q/p;top=top+1;value[top]=r;break;}}}
r=value[top];printf("\nValue of expression is %d",r);}
int pop(){
int ch;ch=value[top];top=top-1;return ch;}
Output
Enter the postfix expression
lmn/+
Enter the value for l10
Enter the value for m5
Enter the value for n5
Value of expression is 11
Result:

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
Ex.No:5A IMPLEMENTATION OF BINARY TREE
Date:
Aim:
To write a C program to implement binary tree.
Algorithm
1. Create a new node and assign values to it
2. insert(node, key)
i) If root == NULL,
return the new node to the calling function.
ii) if root=>data < key
call the insert function with root=>right and assign the return value in root=>right.
root->right = insert(root=>right,key)
iii) if root=>data > key
call the insert function with root->left and assign the return value in root=>left.
root=>left = insert(root=>left,key)
3. Finally, return the original root pointer to the calling function.
Program:
#include<stdio.h>
#include<stdlib.h>
struct node{
int value;
struct node *left_child, *right_child;};
struct node *new_node(int value){
struct node *tmp = (struct node *)malloc(sizeof(struct node));
tmp->value = value;
tmp->left_child = tmp->right_child = NULL;
return tmp;}
void print(struct node *root_node) // displaying the nodes!{
if (root_node != NULL){
print(root_node->left_child);
printf("%d \n", root_node->value);
print(root_node->right_child);}}
struct node* insert_node(struct node* node, int value) // inserting nodes!{
if (node == NULL) return new_node(value);
if (value < node->value){
node->left_child = insert_node(node->left_child, value);}
else if (value > node->value){
node->right_child = insert_node(node->right_child, value);}
return node;}
int main(){
printf("TechVidvan Tutorial: Implementation of a Binary Tree in C!\n\n");
struct node *root_node = NULL;
root_node = insert_node(root_node, 10);
insert_node(root_node, 10);
insert_node(root_node, 30);
insert_node(root_node, 25);
insert_node(root_node, 36);
insert_node(root_node, 56);

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
insert_node(root_node, 78);
print(root_node);
return 0;}
Output:
Implementation of a Binary Tree in C!
10
25
30
36
56
78

Result:

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
Ex.No: 5b IMPLEMENTATION OF BINARY TREE TRAVERSALS
Date:
Aim
To write a C program to implement traversal of a binary tree using pre-order,post-
order, and in-order.
Algorithm:
Step 1: Start
Step 2: If In -order traversal is called until all nodes are traversed −
Step 2.1 :Recursively traverse left subtree.
Step 2.2 : Visit root node.
Step 2.3: Recursively traverse right subtree.
Step 3:If Pre-order traversal Until all nodes are traversed −
Step 3.1 − Visit root node.
Step 3.2 − Recursively traverse left subtree.
Step 3.3− Recursively traverse right subtree.
Step 4: If Post order traversal Until all nodes are traversed −
Step 4.1 − Recursively traverse left subtree.
Step 4.2 − Recursively traverse right subtree.
Step 4.3 − Visit root node.
Step 5: Stop
Program:
#include <stdio.h>
#include <stdlib.h>
struct node {
int item;
struct node* left;
struct node* right;
};
// Inorder traversal
void inorderTraversal(struct node* root) {
if (root == NULL) return;
inorderTraversal(root->left);
printf("%d ->", root->item);
inorderTraversal(root->right);
}
// Preorder traversal
void preorderTraversal(struct node* root) {
if (root == NULL) return;
printf("%d ->", root->item);
preorderTraversal(root->left);
preorderTraversal(root->right);
}

// Postorder traversal
void postorderTraversal(struct node* root) {
if (root == NULL) return;
postorderTraversal(root->left);
postorderTraversal(root->right);

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
printf("%d ->", root->item);
}
// Create a new Node
struct node* createNode(value) {
struct node* newNode = malloc(sizeof(struct node));
newNode->item = value;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
// Insert on the left of the node
struct node* insertLeft(struct node* root, int value) {
root->left = createNode(value);
return root->left;
}
// Insert on the right of the node
struct node* insertRight(struct node* root, int value) {
root->right = createNode(value);
return root->right;
}
int main() {
struct node* root = createNode(1);
insertLeft(root, 2);
insertRight(root, 3);
insertLeft(root->left, 4);
printf("Inorder traversal \n");
inorderTraversal(root);
printf("\nPreorder traversal \n");
preorderTraversal(root);
printf("\nPostorder traversal \n");
postorderTraversal(root);
}
Output:
Inorder traversal
4 ->2 ->1 ->3 ->
Preorder traversal
1 ->2 ->4 ->3 ->
Postorder traversal
4 ->2 ->3 ->1 ->
Result:

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
Ex.No: 6 A,B IMPLEMENTATION OF BINARY SEARCH TREE
Date:
Aim
To implement Binary Search Tree using C.

Algorithm:
Step 1:- Initialize the Structure with value and pointers for left- right node.
Step 2:- Three (preorder, postorder and inorder) operations for depth-first traversal of a tree.
Step 2.1 :- Preorder: Visit a node before traversing it’s sub-trees.
Step 2.2:- Inorder: Visit a node after traversing it’s left subtree but before traversing it’s right
sub-tree.
Step 2.3:- Postorder: Visit a node after traversing all of it’s subtrees.
Step 3:- To find search smallest and largest element compare and go to the left sub tree to find
the min element .
Step 4:- Write a Function to search the appropriate position to insert the new node .
Step 5:- Write a Function to delete a node given by user.
Step 6:- Terminate the execution.
Program:
#include <stdio.h>
#include <stdlib.h>
struct btnode{
int value;
struct btnode *l;
struct btnode *r;
}*root = NULL, *temp = NULL, *t2, *t1;
void delete1();
void insert();
void delete();
void inorder(struct btnode *t);
void create();
void search(struct btnode *t);
void preorder(struct btnode *t);
void postorder(struct btnode *t);
void search1(struct btnode *t,int data);
int smallest(struct btnode *t);
int largest(struct btnode *t);
int flag = 1;
void main(){
int ch;
printf("\nOPERATIONS ---");
printf("\n1 - Insert an element into tree\n");
printf("2 - Delete an element from the tree\n");
printf("3 - Inorder Traversal\n");
printf("4 - Preorder Traversal\n");
printf("5 - Postorder Traversal\n");
printf("6 - Exit\n");
while(1){
printf("\nEnter your choice : ");

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
scanf("%d", &ch);
switch (ch){
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
inorder(root);
break;
case 4:
preorder(root);
break;
case 5:
postorder(root);
break;
case 6:
exit(0);
default :
printf("Wrong choice, Please enter correct choice ");
break; } }} /* To insert a node in the tree */
void insert(){
create();
if (root == NULL)
root = temp;
else
search(root); } /* To create a node */
void create(){
int data;
printf("Enter data of node to be inserted : ");
scanf("%d", &data);
temp = (struct btnode *)malloc(1*sizeof(struct btnode));
temp->value = data;
temp->l = temp->r = NULL;} /* Function to search the appropriate position to insert the new
node */
void search(struct btnode *t){
if ((temp->value > t->value) && (t->r != NULL)) /* value more than root node value
insert at right */
search(t->r);
else if ((temp->value > t->value) && (t->r == NULL))
t->r = temp;
else if ((temp->value < t->value) && (t->l != NULL)) /* value less than root node value
insert at left */
search(t->l);
else if ((temp->value < t->value) && (t->l == NULL))
t->l = temp;} /* recursive function to perform inorder traversal of tree */
void inorder(struct btnode *t){

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
if (root == NULL){
printf("No elements in a tree to display");
return; }
if (t->l != NULL)
inorder(t->l);
printf("%d -> ", t->value);
if (t->r != NULL)
inorder(t->r);} /* To check for the deleted node */
void delete(){
int data;
if (root == NULL){
printf("No elements in a tree to delete");
return; }
printf("Enter the data to be deleted : ");
scanf("%d", &data);
t1 = root;
t2 = root;
search1(root, data);}/* To find the preorder traversal */
void preorder(struct btnode *t){
if (root == NULL){
printf("No elements in a tree to display");
return; }
printf("%d -> ", t->value);
if (t->l != NULL)
preorder(t->l);
if (t->r != NULL)
preorder(t->r);}/* To find the postorder traversal */
void postorder(struct btnode *t){
if (root == NULL){
printf("No elements in a tree to display ");
return;}
if (t->l != NULL)
postorder(t->l);
if (t->r != NULL)
postorder(t->r);
printf("%d -> ", t->value);} /* Search for the appropriate position to insert the new node */
void search1(struct btnode *t, int data){
if ((data>t->value)){
t1 = t;
search1(t->r, data);}
else if ((data < t->value)) {
t1 = t;
search1(t->l, data); }
else if ((data==t->value)){
delete1(t);}}/* To delete a node */
void delete1(struct btnode *t){
int k; /* To delete leaf node */
if ((t->l == NULL) && (t->r == NULL)){

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
if (t1->l == t){
t1->l = NULL; }
else{
t1->r = NULL;}
t = NULL;
free(t);
return;} /* To delete node having one left hand child */
else if ((t->r == NULL)){
if (t1 == t){
root = t->l;
t1 = root;}
else if (t1->l == t){
t1->l = t->l; }
else{
t1->r = t->l;}
t = NULL;
free(t);
return;} /* To delete node having right hand child */
else if (t->l == NULL){
if (t1 == t) {
root = t->r;
t1 = root;}
else if (t1->r == t)
t1->r = t->r;
else
t1->l = t->r;
t == NULL;
free(t);
return; }/* To delete node having two child */
else if ((t->l != NULL) && (t->r != NULL)) {
t2 = root;
if (t->r != NULL) {
k = smallest(t->r);
flag = 1;}
else{
k =largest(t->l);
flag = 2;}
search1(root, k);
t->value = k;}}/* To find the smallest element in the right sub tree */
int smallest(struct btnode *t){
t2 = t;
if (t->l != NULL) {
t2 = t;
return(smallest(t->l));}
else
return (t->value);}/* To find the largest element in the left sub tree */
int largest(struct btnode *t){
if (t->r != NULL) {

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
t2 = t;
return(largest(t->r));}
else
return(t->value);}
Output:
OPERATIONS ---
1 - Insert an element into tree
2 - Delete an element from the tree
3 - Inorder Traversal
4 - Preorder Traversal
5 - Postorder Traversal
6 - Exit

Enter your choice : 1


Enter data of node to be inserted : 10
Enter your choice : 1
Enter data of node to be inserted : 20
Enter your choice : 1
Enter data of node to be inserted : 30
Enter your choice : 1
Enter data of node to be inserted : 40
Enter your choice : 2
Enter the data to be deleted : 40
Enter your choice : 3
10 -> 20 -> 30 ->
Enter your choice : 4
10 -> 20 -> 30 ->
Enter your choice : 5
30 -> 20 -> 10 ->
Enter your choice :

Result:

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT

Ex.No:7A Implementation of AVL Tree


Date:
Aim:
To write a C program to implement AVL Tree.
Algorithm:
Step 1:- Initialize the Structure with balance and pointer for left, right node .
Step 2:- Write a Function for insertion operation.
Step 3:- Read the insert element from the user
Step 4:- Insert the new element into the tree using Binary Search Tree insertion logic.
Step 5:- After insertion, check the Balance Factor of every node.
Step 6:- If the Balance Factor of every node is 0 or 1 or -1 then go for next operation.
Step 7:- If the Balance Factor of any node is other than 0 or 1 or -1 then tree is said to be
imbalanced. Step 8:- Then perform the suitable single(LL or RR) or double(LR or RL) Rotation
to make it balanced. And then terminate the program.

Program:
#include<stdio.h>
#include<malloc.h>
typedef enum { FALSE ,TRUE } bool;
struct node{
int info;
int balance;
struct node *lchild;
struct node *rchild;};
struct node *insert (int , struct node *, int *);
struct node* search(struct node *,int);
main(){
bool ht_inc;
int info ;
int choice;
struct node *root = (struct node *)malloc(sizeof(struct node));
root = NULL;
while(1) {
printf("1.Insert\n");
printf("2.Display\n");
printf("3.Quit\n");
printf("Enter your choice : ");
scanf("%d",&choice);
switch(choice){
case 1:
printf("Enter the value to be inserted : ");
scanf("%d", &info);
if( search(root,info) == NULL )
root = insert(info, root, &ht_inc);
else
printf("Duplicate value ignored\n");
break;

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
case 2:
if(root==NULL){
printf("Tree is empty\n");
continue;}
printf("Tree is :\n");
display(root, 1);
printf("\n\n");
printf("Inorder Traversal is: ");
inorder(root);
printf("\n");
break;
case 3:
exit(1);
default:
printf("Wrong choice\n"); }/*End of switch*/ }/*End of while*/}/*End of main()*/
struct node* search(struct node *ptr,int info){
if(ptr!=NULL)
if(info < ptr->info)
ptr=search(ptr->lchild,info);
else if( info > ptr->info)
ptr=search(ptr->rchild,info);
return(ptr);}/*End of search()*/
struct node *insert (int info, struct node *pptr, int *ht_inc){
struct node *aptr;
struct node *bptr;
if(pptr==NULL){
pptr = (struct node *) malloc(sizeof(struct node));
pptr->info = info;
pptr->lchild = NULL;
pptr->rchild = NULL;
pptr->balance = 0;
*ht_inc = TRUE;
return (pptr); }
if(info < pptr->info){
pptr->lchild = insert(info, pptr->lchild, ht_inc);
if(*ht_inc==TRUE){
switch(pptr->balance){
case -1: /* Right heavy */
pptr->balance = 0;
*ht_inc = FALSE;
break;
case 0: /* Balanced */
pptr->balance = 1;
break;
case 1: /* Left heavy */
aptr = pptr->lchild;
if(aptr->balance == 1){
printf("Left to Left Rotation\n");

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
pptr->lchild= aptr->rchild;
aptr->rchild = pptr;
pptr->balance = 0;
aptr->balance=0;
pptr = aptr;}
else {
printf("Left to right rotation\n");
bptr = aptr->rchild;
aptr->rchild = bptr->lchild;
bptr->lchild = aptr;
pptr->lchild = bptr->rchild;
bptr->rchild = pptr;
if(bptr->balance == 1 )
pptr->balance = -1;
else
pptr->balance = 0;
if(bptr->balance == -1)
aptr->balance = 1;
else
aptr->balance = 0;
bptr->balance=0;
pptr=bptr; }
*ht_inc = FALSE;}/*End of switch */ }/*End of if */ }/*End of if*/
if(info > pptr->info){
pptr->rchild = insert(info, pptr->rchild, ht_inc);
if(*ht_inc==TRUE){
switch(pptr->balance){
case 1: /* Left heavy */
pptr->balance = 0;
*ht_inc = FALSE;
break;
case 0: /* Balanced */
pptr->balance = -1;
break;
case -1: /* Right heavy */
aptr = pptr->rchild;
if(aptr->balance == -1){
printf("Right to Right Rotation\n");
pptr->rchild= aptr->lchild;
aptr->lchild = pptr;
pptr->balance = 0;
aptr->balance=0;
pptr = aptr;}
else{
printf("Right to Left Rotation\n");
bptr = aptr->lchild;
aptr->lchild = bptr->rchild;
bptr->rchild = aptr;

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
pptr->rchild = bptr->lchild;
bptr->lchild = pptr;
if(bptr->balance == -1)
pptr->balance = 1;
else
pptr->balance = 0;
if(bptr->balance == 1)
aptr->balance = -1;
else
aptr->balance = 0;
bptr->balance=0;
pptr = bptr;}/*End of else*/
*ht_inc = FALSE; }/*End of switch */}/*End of if*/}/*End of if*/
return(pptr);}/*End of insert()*/
display(struct node *ptr,int level){
int i;
if ( ptr!=NULL ){
display(ptr->rchild, level+1);
printf("\n");
for (i = 0; i < level; i++)
printf(" ");
printf("%d", ptr->info);
display(ptr->lchild, level+1); }/*End of if*/}/*End of display()*/
inorder(struct node *ptr){
if(ptr!=NULL){
inorder(ptr->lchild);
printf("%d ",ptr->info);
inorder(ptr->rchild); }}/*End of inorder()*/
Output:
1.Insert 2.Display 3.Quit
Enter your choice : 1
Enter the value to be inserted : 11
1.Insert 2.Display 3.Quit
Enter your choice : 1
Enter the value to be inserted : 22
1.Insert 2.Display 3.Quit
Enter your choice : 1
Enter the value to be inserted : 33
Right to Right Rotation
1.Insert 2.Display 3.Quit
Enter your choice : 2
Tree is : 33 22 11
Inorder Traversal is: 11 22 33
1.Insert 2.Display 3.Quit
Enter your choice : 3
Quit
Result:

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
Ex.No: 7B Implementation of heap using Priority Queue
Date:
Aim:
To write a C program to implement heap using priority Queue.
Algorithm:
Step 1:- Initialize the Structure with priority, information and pointer to next node .
Step 2:- Write a Function for insertion, deletion and display operation.
Step 3:- Read the insert element and its priority from the user.
Step 4:- Insert the element according to the priority in appropriate node.
Step 5:- Delete the queue using del function, display “QUEUE UNDERFLOW” if null.
Step 6:- Display the queue with separate function and terminate the execution
Program:
#include<stdio.h>
#include<malloc.h>
void insert();
void del();
void display();
struct node{
int priority;
int info;
struct node *next;
}*start=NULL,*q,*temp,*new;
typedef struct node N;
int main(){
int ch;
do{
printf("\n[1] INSERTION\t[2] DELETION\t[3] DISPLAY [4] EXIT\t:");
scanf("%d",&ch);
switch(ch){
case 1:insert();
break;
case 2:del();
break;
case 3:display();
break;
case 4:
break;}}
while(ch<4);}
void insert(){
int item,itprio;
new=(N*)malloc(sizeof(N));
printf("ENTER THE ELT.TO BE INSERTED :\t");
scanf("%d",&item);
printf("ENTER ITS PRIORITY :\t");
scanf("%d",&itprio);
new->info=item;
new->priority=itprio;
new->next=NULL;

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
if(start==NULL ){//new->next=start;
start=new;}
else if(start!=NULL&&itprio<=start->priority){ new->next=start;
start=new;}
else{
q=start;
while(q->next != NULL && q->next->priority<=itprio)
{q=q->next;}
new->next=q->next;
q->next=new;}}
void del(){
if(start==NULL){
printf("\nQUEUE UNDERFLOW\n"); }
else{
new=start;
printf("\nDELETED ITEM IS %d\n",new->info);
start=start->next;
//free(start);}}
void display(){
temp=start;
if(start==NULL)
printf("QUEUE IS EMPTY\n");
else{
printf("QUEUE IS:\n");
if(temp!=NULL)
for(temp=start;temp!=NULL;temp=temp->next){
printf("\n%d priority =%d\n",temp->info,temp->priority);
//temp=temp->next;}}}
Output:
[1] INSERTION [2] DELETION [3] DISPLAY [4] EXIT :1
ENTER THE ELT.TO BE INSERTED : 10
ENTER ITS PRIORITY : 1
[1] INSERTION [2] DELETION [3] DISPLAY [4] EXIT :1
ENTER THE ELT.TO BE INSERTED : 20
ENTER ITS PRIORITY : 2
[1] INSERTION [2] DELETION [3] DISPLAY [4] EXIT :1
ENTER THE ELT.TO BE INSERTED : 30
ENTER ITS PRIORITY : 3
[1] INSERTION [2] DELETION [3] DISPLAY [4] EXIT :2
DELETED ITEM IS 10
[1] INSERTION [2] DELETION [3] DISPLAY [4] EXIT :3
QUEUE IS:
20 priority =2
30 priority =3
[1] INSERTION [2] DELETION [3] DISPLAY [4] EXIT :4
Result:

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT

Ex.No: 8.A Dijkstra's single source shortest path algorithm.


Date:
Aim:
To write a C program to implement Dijkstra's single source shortest path algorithm.
Algorithm:
Step 1: Start
Step 2:Create a set sptSet (shortest path tree set) that keeps track of vertices included in the
shortest-path tree.
Step 3: Assign a distance value to all vertices in the input graph. Initialize all distance values
as INFINITE. Assign the distance value as 0 for the source vertex so that it is picked first.
Step 4:While sptSet doesn’t include all vertices
Step 5:Pick a vertex u which is not there in sptSet and has a minimum distance value.
Step 6:Include u to sptSet.
Step 7:Then update distance value of all adjacent vertices of u.
Step 8:To update the distance values, iterate through all adjacent vertices.
Step 9:For every adjacent vertex v, if the sum of the distance value of u (from source) and weight
of edge u-v, is less than the distance value of v, then update the distance value of v.
Program:
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#define V 4
int minDistance(int dist[], bool sptSet[]){// Initialize min value
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
if (sptSet[v] == false && dist[v] <= min)
min = dist[v], min_index = v;
return min_index}
void printSolution(int dist[]){
printf("Vertex \t\t Distance from Source\n");
for (int i = 0; i < V; i++)
printf("%d \t\t\t\t %d\n", i, dist[i]);}
void dijkstra(int graph[V][V], int src){
int dist[V];
bool sptSet[V];
for (int i = 0; i < V; i++)
dist[i] = INT_MAX, sptSet[i] = false;
dist[src] = 0;
for (int count = 0; count < V - 1; count++) {
int u = minDistance(dist, sptSet);
sptSet[u] = true;
for (int 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];}

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
printSolution(dist);}
int main(){
int graph[V][V] = { { 0, 4, 0, 0},
{ 4, 0, 8, 0 },
{ 0, 8, 0, 7 },
{ 0, 0, 7, 0 } };
dijkstra(graph, 0);
return 0;}
Output:
Vertex Distance from Source
0 0
1 4
2 12
3 19

Result:

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
Ex.No: 8.B Floyd Warshall Algorithm
Date:
Aim:
To write a C program to implement Dijkstra's single source shortest path algorithm.
Algorithm:
Step 1 :Initialize the solution matrix same as the input graph matrix as a first step.
Step 2:Then update the solution matrix by considering all vertices as an intermediate vertex.
Step 3:The idea is to one by one pick all vertices and updates all shortest paths which include the
picked vertex as an intermediate vertex in the shortest path.
Step 4:When we pick vertex number k as an intermediate vertex, we already have considered
vertices {0, 1, 2, .. k-1} as intermediate vertices.
Step 5:For every pair (i, j) of the source and destination vertices respectively, there are two
possible cases.
Step 6:k is not an intermediate vertex in shortest path from i to j. We keep the value of dist[i][j]
as it is.
Step 7:k is an intermediate vertex in shortest path from i to j. We update the value of dist[i][j] as
dist[i][k] + dist[k][j] if dist[i][j] > dist[i][k] + dist[k][j]
Step 8:Stop
Program:
#include<stdio.h>
void floyd(int a[4][4], int n)
{ for(int k=0;k<n;k++){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(a[i][j]>a[i][k]+a[k][j]){
a[i][j]=a[i][k]+a[k][j];} } }}
printf("All Pairs Shortest Path is :\n");
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
printf("%d ",a[i][j]);}
printf("\n");}}
int main(){
int cost[4][4] = {{0, 2, 10, 999}, {999, 0, 3, 6}, {8, 999, 0, 4}, {7, 999, 999, 0}};
int n = 4;
floyd(cost,n);}
Output:
All Pairs Shortest Path is :
0258
11 0 3 6
8 10 0 4
7 9 12 0
Result:

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
Ex.No: 9.A. Implementation of Kruskal’s algorithm
Date:
Aim:
To write the C program to implement Kruskal’s algorithm
Algorithm:
1. Create a Graph by adding vertices and assign weight for each edges.
2. Sort all the edges from low weight to high
3. Take the edge with the lowest weight and add it to the spanning tree.
4. If adding the edge created a cycle, then reject this edge.
5. Keep adding edges until we reach all vertices.
6. Finally we will get a spanning tree with minimum cost.
Program:
#include <stdio.h>
#include <stdlib.h>
int i, j, k, a, b, u, v, n, ne = 1;
int min, mincost = 0, cost[9][9], parent[9];
int find(int);
int uni(int, int);
void main(){
printf("Kruskal's algorithm in C\n");
printf("========================\n");
printf("Enter the no. of vertices:\n");
scanf("%d", &n);
printf("\nEnter the cost adjacency matrix:\n");
for (i = 1; i <= n; i++){
for (j = 1; j <= n; j++) {
scanf("%d", &cost[i][j]);
if (cost[i][j] == 0)
cost[i][j] = 999;} }
printf("The edges of Minimum Cost Spanning Tree are\n");
while (ne < n) {
for (i = 1, min = 999; i <= n; i++) {
for (j = 1; j <= n; j++){
if (cost[i][j] < min){
min = cost[i][j];
a = u = i;
b = v = j; }}}
u = find(u);
v = find(v);
if (uni(u, v)) {
printf("%d edge (%d,%d) =%d\n", ne++, a, b, min);
mincost += min;}
cost[a][b] = cost[b][a] = 999;}
printf("\nMinimum cost = %d\n", mincost);}
int find(int i){
while (parent[i])
i = parent[i];
return i;}

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
int uni(int i, int j){
if (i != j){
parent[j] = i;
return 1;}
return 0;}
Output:
Kruskal's algorithm in C
========================
Enter the no. of vertices:6
Enter the cost adjacency matrix:
031600
305030
150564
605002
036006
004260
The edges of Minimum Cost Spanning Tree are
1 edge (1,3) =1
2 edge (4,6) =2
3 edge (1,2) =3
4 edge (2,5) =3
5 edge (3,6) =4
Minimum cost = 13

Result:

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
Ex.No: 9.B Implementation of Prim’s Algorithm
Date:
Aim:
To write the C program to implement Prim’s Algorithm
Algorithm:
1. First, we have to initialize an MST with the randomly chosen vertex.
2. Now, we have to find all the edges that connect the tree in the above step with the new
vertices.
3. From the edges found, select the minimum edge and add it to the tree.
4. Repeat step 2 until the minimum spanning tree is formed.
Program:
#include<stdio.h>
#include<stdbool.h>
#define INF 9999999
#define V 5
int G[V][V] = {
{0, 9, 75, 0, 0},
{9, 0, 95, 19, 42},
{75, 95, 0, 51, 66},
{0, 19, 51, 0, 31},
{0, 42, 66, 31, 0}};
int main() {
int no_edge;
int selected[V];
memset(selected, false, sizeof(selected));
no_edge = 0;
selected[0] = true;
int x;
int y;
printf("Edge : Weight\n");
while (no_edge < V - 1) {
int min = INF;

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
x = 0;
y = 0;
for (int i = 0; i < V; i++) {
if (selected[i]) {
for (int j = 0; j < V; j++) {
if (!selected[j] && G[i][j]) {
if (min > G[i][j]) {
min = G[i][j];
x = i;
y = j;
} }
}}}
printf("%d - %d : %d\n", x, y, G[x][y]);
selected[y] = true;
no_edge++;
}
return 0;
}

Output:
Edge : Weight
0-1:9
1 - 3 : 19
3 - 4 : 31
3 - 2 : 51

Result:

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
Ex.No: 10 A,B Implementation of BFS and DFS on a graph represented using adjacency
list
Date:
Aim:
To write the C program to implement BFS and DFS on a graph represented using
adjacency list
Algorithm:
Step 1:- Initialize the Structure with data, vertex and pointer to next node .
Step 2:- Write a readgraph function to create adjacency list.
Step 3:- In BFS, insert all unvisited, adjacent vertices of v into queue.
Step 4:-In readgraph, display the graph with search result with enqueuer and dequeue.
Step 5:- Create DFS function with backtracking property.
Step 6:- Terminate the execution.
Program:
#include<stdio.h>
#include<stdlib.h>
#define MAX 20
typedef struct Q
{
int data[MAX];
int R,F;
}Q;
typedef struct node
{
struct node *next;
int vertex;
}node;
void enqueue(Q *,int);
int dequque(Q *);
int empty(Q *);
int full(Q *);
void BFS(int);
void readgraph(); //create an adjecency list
void insert(int vi,int vj); //insert an edge (vi,vj)in adj.list
void DFS(int i);
int visited[MAX];
node *G[20]; //heads of the linked list
int n; // no of nodes
void main(){
int i,op;
do{ printf("\n\n1)Create\n2)BFS\n3)DFS\n4)Quit");
printf("\nEnter Your Choice: ");
scanf("%d",&op);
switch(op)
{ case 1:readgraph();break;
case 2:printf("\nStarting Node No. : ");
scanf("%d",&i);
BFS(i);break;

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
case 3:for(i=0;i<n;i++)
visited[i]=0;
printf("\nStarting Node No. : ");
scanf("%d",&i);
DFS(i);break; }
}while(op!=4);}
void BFS(int v)
{
int w,i,visited[MAX];
Q q;
node *p;
q.R=q.F=-1; //initialize
for(i=0;i<n;i++)
visited[i]=0;
enqueue(&q,v);
printf("\nVisit\t%d",v);
visited[v]=1;
while(!empty(&q)){
v=dequeue(&q); //insert all unvisited,adjacent vertices of v into queue
for(p=G[v];p!=NULL;p=p->next) {
w=p->vertex;
if(visited[w]==0){
enqueue(&q,w);
visited[w]=1;
printf("\nvisit\t%d",w);
} } }}
void DFS(int i)
{
node *p;
printf("\n%d",i);
p=G[i];
visited[i]=1;
while(p!=NULL)
{
i=p->vertex;
if(!visited[i])
DFS(i);
p=p->next;
}}
int empty(Q *P){
if(P->R==-1)
return(1);
return(0);}
int full(Q *P){
if(P->R==MAX-1)
return(1);
return(0);
}void enqueue(Q *P,int x){

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
if(P->R==-1){
P->R=P->F=0;
P->data[P->R]=x;
} else{
P->R=P->R+1;
P->data[P->R]=x;}}
int dequeue(Q *P){
int x;
x=P->data[P->F];
if(P->R==P->F) {
P->R=-1;
P->F=-1; }
else
P->F=P->F+1;
return(x);}
void readgraph()
{ int i,vi,vj,no_of_edges;
printf("\nEnter no. of vertices :");
scanf("%d",&n); //initialise G[] with NULL
for(i=0;i<n;i++)
G[i]=NULL;//read edges and insert them in G[]
printf("\nEnter no of edges :");
scanf("%d",&no_of_edges);
for(i=0;i<no_of_edges;i++){
printf("\nEnter an edge (u,v) :");
scanf("%d%d",&vi,&vj);
insert(vi,vj);
insert(vj,vi);}}
void insert(int vi,int vj)
{
node *p,*q;
//acquire memory for the new node
q=(node *)malloc(sizeof(node));
q->vertex=vj;
q->next=NULL; //insert the node in the linked list for the vertex no. vi
if(G[vi]==NULL)
G[vi]=q;
else{ // go to the end of linked list
p=G[vi];
while(p->next!=NULL)
p=p->next;
p->next=q;
}}

Output:
1)Create
2)BFS
3)DFS

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
4)Quit
Enter Your Choice: 1
Enter no. of vertices :4
Enter no of edges :5
Enter an edge (u,v) :1 2
Enter an edge (u,v) :2 3
Enter an edge (u,v) :3 4
Enter an edge (u,v) :4 1
Enter an edge (u,v) :1 3
1)Create
2)BFS
3)DFS
4)Quit
Enter Your Choice: 2
Starting Node No. : 1
Visit 1
visit 2
visit 3
visit 4
1)Create
2)BFS
3)DFS
4)Quit
Enter Your Choice: 3
Starting Node No. :2
2
1
4
3
1)Create
2)BFS
3)DFS
4)Quit
Enter Your Choice: 2
Starting Node No. : 4
Visit 4
visit 3
visit 1
visit 2
1)Create
2)BFS
3)DFS
4)Quit
Enter Your Choice: 4
Result:

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
Ex.No: 10 C Topological Sorting
Date:
Aim:
To write a C program to implement Topological Sorting.
Algorithm:
Step 1:Create a stack to store the nodes.
Step2:Initialize visited array of size N to keep the record of visited nodes.
Step 3:Run a loop from 0 till N
Step 4:if the node is not marked True in visited array.
Step 5:Call the recursive function for topological sort and perform the following steps.
Step6:Mark the current node as True in the visited array.
Step7:Run a loop on all the nodes which has a directed edge to the current node
Step8:if the node is not marked True in the visited array:
Step9:Recursively call the topological sort function on the node
Step 10:Push the current node in the stack.
Step 11:Print all the elements in the stack.
Step 12: Stop

Program:
#include<stdio.h>
#include<stdlib.h>
#define MAX 100
int n; /*Number of vertices in the graph*/
int adj[MAX][MAX]; /*Adjacency Matrix*/
void create_graph();
int queue[MAX], front = -1,rear = -1;
void insert_queue(int v);
int delete_queue();
int isEmpty_queue();
int indegree(int v);
int main()
{
int i,v,count,topo_order[MAX],indeg[MAX];
create_graph();
/*Find the indegree of each vertex*/
for(i=0;i<n;i++)
{
indeg[i] = indegree(i);
if( indeg[i] == 0 )
insert_queue(i);
}
count = 0;
while( !isEmpty_queue( ) && count < n )
{
v = delete_queue(); topo_order[++count] = v; /*Add vertex v to topo_order array*/
/*Delete all edges going fron vertex v */

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
for(i=0; i<n; i++)
{
if(adj[v][i] == 1)
{
adj[v][i] = 0;
indeg[i] = indeg[i]-1;
if(indeg[i] == 0)
insert_queue(i);
}
}
}

if( count < n )


{
printf("\nNo topological ordering possible, graph contains cycle\n");
exit(1);
}
printf("\nVertices in topological order are :\n");
for(i=1; i<=count; i++)
printf( "%d ",topo_order[i] );
printf("\n");

return 0;
}/*End of main()*/

void insert_queue(int vertex)


{
if (rear == MAX-1)
printf("\nQueue Overflow\n");
else
{
if (front == -1) /*If queue is initially empty */
front = 0;
rear = rear+1;
queue[rear] = vertex ;
}
}/*End of insert_queue()*/

int isEmpty_queue()
{
if(front == -1 || front > rear )
return 1;
else
return 0;
}/*End of isEmpty_queue()*/

int delete_queue()
{

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
int del_item;
if (front == -1 || front > rear)
{
printf("\nQueue Underflow\n");
exit(1);
}
else
{
del_item = queue[front];
front = front+1;
return del_item;
}
}/*End of delete_queue() */

int indegree(int v)
{
int i,in_deg = 0;
for(i=0; i<n; i++)
if(adj[i][v] == 1)
in_deg++;
return in_deg;
}/*End of indegree() */

void create_graph()
{
int i,max_edges,origin,destin;

printf("\nEnter number of vertices : ");


scanf("%d",&n);
max_edges = n*(n-1);

for(i=1; i<=max_edges; i++)


{
printf("\nEnter edge %d(-1 -1 to quit): ",i);
scanf("%d %d",&origin,&destin);

if((origin == -1) && (destin == -1))


break;

if( origin >= n || destin >= n || origin<0 || destin<0)


{
printf("\nInvalid edge!\n");
i--;
}
else
adj[origin][destin] = 1;
}
}

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT

Output
Enter number of vertices : 6
Enter edge 1(-1 -1 to quit): 0 1
Enter edge 2(-1 -1 to quit): 0 2
Enter edge 3(-1 -1 to quit): 0 3
Enter edge 4(-1 -1 to quit): 1 3
Enter edge 5(-1 -1 to quit): 2 4
Enter edge 6(-1 -1 to quit): 2 5
Enter edge 7(-1 -1 to quit): 3 5
Enter edge 8(-1 -1 to quit): 4 5
Enter edge 9(-1 -1 to quit): 1 5
Enter edge 10(-1 -1 to quit): -1 -1
Vertices in topological order are :
012345

Result:

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT

Ex.No: 11 A INSERTION SORT


Date:
Aim
To write a C program to implement insertion sort.
Algorithm
1. If it is the first element, it is already sorted. return 1;
2. Pick next element
3. Compare with all elements in the sorted sub-list
4. Shift all the elements in the sorted sub-list that is greater than the value to be sorted
5. Insert the value
6. Repeat until list is sorted
Program:
#include <math.h>
#include <stdio.h>/* Function to sort an array using insertion sort*/
void insertionSort(int arr[], int n){
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;/* Move elements of arr[0..i-1], that are greater than key, to one position ahead of
their current position */
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];j = j - 1;}
arr[j + 1] = key;}}// A utility function to print an array of size n
void printArray(int arr[], int n){
int i;
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");}/* Driver program to test insertion sort */
int main()
{
int arr[] = { 12, 11, 13, 5, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
insertionSort(arr, n);
printArray(arr, n);
return 0;
}

Output

5 6 11 12 13

Result:

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
11 A SELECTION SORT
Date:
Aim
To write a C program to implement selection sort.
Algorithm
Step 1 − Set min to the first location
Step 2 − Search the minimum element in the array
Step 3 – swap the first location with the minimum value in the array
Step 4 – assign the second element as min.
Step 5 − Repeat the process until we get a sorted array.
Program:
#include <stdio.h>
void swap(int *xp, int *yp){
int temp = *xp;
*xp = *yp;
*yp = temp;}
void selectionSort(int arr[], int n){
int i, j, min_idx;
for (i = 0; i < n-1; i++){
min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
if(min_idx != i)
swap(&arr[min_idx], &arr[i]);}}/* Function to print an array */
void printArray(int arr[], int size){
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");}
int main(){
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr)/sizeof(arr[0]);
selectionSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;}
Output:
Sorted array:
11 12 22 25 64

Result:

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT

Ex.No: 11 A QUICK SORT


Date:
Aim
To write a C program to implement quick sort.
Algorithm
Step 1 - Consider the first element of the list as pivot (i.e., Element at first position in the list).
Step 2 - Define two variables i and j. Set i and j to first and last elements of the list respectively.
Step 3 - Increment i until a[i] > pivot then stop.
Step 4 - Decrement j until a[j] < pivot then stop.
Step 5 - If i < j then exchange a[i] and a[j].
Step 6 - Repeat steps 3,4 & 5 until i > j.
Step 7 - Exchange the pivot element with a[j] element.
Program:
#include <stdio.h>
int partition (int a[], int start, int end)
{
int pivot = a[end]; // pivot element
int i = (start - 1);

for (int j = start; j <= end - 1; j++)


{
if (a[j] < pivot)
{
i++;
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
int t = a[i+1];
a[i+1] = a[end];
a[end] = t;
return (i + 1);
}

void quick(int a[], int start, int end)


{
if (start < end)
{
int p = partition(a, start, end); //p is the partitioning index
quick(a, start, p - 1);
quick(a, p + 1, end);
}
}

void printArr(int a[], int n)


{

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
int i;
for (i = 0; i < n; i++)
printf("%d ", a[i]);
}
int main()
{
int a[] = { 24, 9, 29, 14, 19, 27 };
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");
printArr(a, n);
quick(a, 0, n - 1);
printf("\nAfter sorting array elements are - \n");
printArr(a, n);

return 0;
}

Output
Before sorting array elements are -
24 9 29 14 19 27
After sorting array elements are -
9 14 19 24 27 29

Result:

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
Ex.No: 11 A MERGE SORT
Date:
Aim
To write a C program to implement merge sort.
Algorithm
Step 1: Find the middle index of the array.
Middle = 1 + (last – first)/2
Step 2: Divide the array from the middle.
Step 3: Call merge sort for the first half of the array
MergeSort(array, first, middle)
Step 4: Call merge sort for the second half of the array.
MergeSort(array, middle+1, last)
Step 5: Merge the two sorted halves into a single sorted array.
Program:
#include <stdio.h>
#include <stdlib.h>
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int L[n1], R[n2];
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];
i = 0;
j = 0;
k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
k++;
}
}
void mergeSort(int arr[], int l, int r)
{
if (l < r) {
int m = l + (r - l) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
void printArray(int A[], int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", A[i]);
printf("\n");
}
int main()
{
int arr[] = { 12, 11, 13, 5, 6, 7 };
int arr_size = sizeof(arr) / sizeof(arr[0]);

printf("Given array is \n");


printArray(arr, arr_size);

mergeSort(arr, 0, arr_size - 1);

printf("\nSorted array is \n");


printArray(arr, arr_size);
return 0;
}
Output:
Given array is
12 11 13 5 6 7
Sorted array is
5 6 7 11 12 13

Result:

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
Ex.No: 11.B LINEAR SEARCH
Date:
Aim
To write a C program to implement linear search.
Algorithm
Step1: Get the total number of elements and the elements.
Step2: Get the key to be searched.
Step3: Each element in the array is checked with the key.
Step4: If the element is equal to key, the element is found and displays the location of the key.
Step5:Otherwise, the element is not found.
Program
#include<stdio.h>
void main()
{
int array[100],search,c,n;
printf("Enter the Number of elements\n");
scanf("%d",&n);
printf("Enter the Elements\n");
for (c=0; c<n;c++)
scanf("%d", &array[c]);
printf("Enter the number to search\n");
scanf("%d", &search);
for(c=0;c<n;c++)
{
if(array[c] == search)
{
printf("%d is present at location %d.\n",search,c+1);
break;
}
}
if(c==n)
{
printf("%d is not present in array.\n",search);
} //return 0;
}

Output
Enter the Number of elements
4
Enter the Elements
4 3 2 1
Enter the number to search 2
2 is present at location 3.
Result:

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
Ex.No: 11.B BINARY SEARCH
Date:
Aim
To write a C program to implement binary search.

Algorithm
Step1:-Get the number of elements, elements and the key to be searched.
Step2:-Sort the list in non-decreasing order.
Step 3:-Initialize low = 0, high = number_of_elements and mid = floor((low+high)/2).
(i) If the middle element (mid) is less than key then key has to present in range [mid+1
, high], so low=mid+1, high remains unchanged and mid is adjusted accordingly
(ii) If middle element is the key, then the element is found.
(iii) If the middle element is greater than key then key has to be present in the range
[low,mid-1], so high=mid-1, low remains unchanged and mid is adjusted accordingly.
Step 4:-Repeat the step until low is less than or equal to high or the position of the ‘input key’
has been found.
Program
#include<stdio.h>
int BinarySearch(int *array, int n, int key)
{
int low = 0, high = n-1, mid;
while(low <= high)
{
mid = (low + high)/2;
if(array[mid] < key)
{
low = mid + 1;
}
else if(array[mid] == key)
{
return mid;
}
else if(array[mid] > key)
{
high = mid-1;
}
}
return -1;
}
int main()
{
int n=5;
int array[n];
int i,key,index;
printf("\nEnter the 5 elements");
//scanf("%d",&n);
printf("\nEnter the elements");
for(i = 0;i < n;i++)

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
{
scanf("%d",&array[i]);
}
for(i = 1;i < n;i++)
{
if(array[i] < array[i - 1])
{
printf("Given input is not sorted\n");
return 0;
}
}
printf("Enter the key to be searched");
scanf("%d",&key);
index = BinarySearch(array,n,key);
if(index==-1)
{
printf("Element not found\n");
}
else
{
printf("Element is at index %d\n",index);
}
return 0;
}
Output

Enter the 5 elements


Enter the elements10
102
104
108
101
Enter the key to be searched10
Element is at index 0

Result:

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
Ex.No:11 C Implementation of Hashing using Linear and Quatratic Probing
Date:
Aim:
To write a C program to implement Hashing using Linear and quatratic Probing
Algorithm:
Step1:- For linear probing, calculate a hash code from the key
Step 2:- Access that hash element If the hash element is empty, add straight away If not, probe
through subsequent elements (looping back if necessary), trying to find a free place If a free
place is found, add the data at that position If no free place is found, the add will fail.
Step 3:- Quadratic probing operates by taking the original hash value
Step 4:- Then add successive values of an arbitrary quadratic polynomial to the starting value.
Step 5:- Terminate the execution.
Program:
#include <stdio.h>
int tsize;
int hasht(int key)
{
int i ;
i = key%tsize ;
return i;
}//-------LINEAR PROBING-------
int rehashl(int key)
{
int i ;
i = (key+1)%tsize ;
return i ;
}//-------QUADRATIC PROBING-------
int rehashq(int key, int j)
{
int i ;
i = (key+(j*j))%tsize ;
return i ;
}
void main()
{
int key,arr[20],hash[20],i,n,s,op,j,k ;
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{

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT
printf("\n\n1.Linear Probing\n2.Quadratic Probing \n3.Exit \nEnter your option: ");
scanf("%d",&op);
switch(op)
{
case 1:
for (i=0;i<tsize;i++)
hash[i]=-1 ;
for(k=0;k<n;k++) {
key=arr[k] ;
i = hasht(key);
while (hash[i]!=-1)
{
i = rehashl(i);
}
hash[i]=key ;
}
printf("\nThe elements in the array are: ");
for (i=0;i<tsize;i++)
{
printf("\n Element at position %d: %d",i,hash[i]);
}
break ;
case 2:
for (i=0;i<tsize;i++)
hash[i]=-1 ;
for(k=0;k<n;k++)
{
j=1;
key=arr[k] ;
i = hasht(key);
while (hash[i]!=-1)
{
i = rehashq(i,j);
j++ ;
}
hash[i]=key ;
}
printf("\nThe elements in the array are: ");
for (i=0;i<tsize;i++)
{
printf("\n Element at position %d: %d",i,hash[i]);
}
break ;
}
}while(op!=3);
}
Output:
Enter the size of the hash table: 10

St. Joseph’s College of Engineering


CS1307 – Data Structures Lab 2024-2025 Department of IT

Enter the number of elements: 8


Enter Elements: 72 27 36 24 63 81 92 101
1.Linear Probing
2.Quadratic Probing
3.Exit
Enter your option: 1
The elements in the array are:
Element at position 0: -1
Element at position 1: 81
Element at position 2: 72
Element at position 3: 63
Element at position 4: 24
Element at position 5: 92
Element at position 6: 36
Element at position 7: 27
Element at position 8: 101
Element at position 9: -1
1.Linear Probing
2.Quadratic Probing
3.Exit
Enter your option: 2
The elements in the array are:
Element at position 0: -1
Element at position 1: 81
Element at position 2: 72
Element at position 3: 63
Element at position 4: 24
Element at position 5: 101
Element at position 6: 36
Element at position 7: 27
Element at position 8: 92
Element at position 9: -1
1.Linear Probing
2.Quadratic Probing
3.Exit
Enter your option: 3

Result:

St. Joseph’s College of Engineering

You might also like