0% found this document useful (0 votes)
7 views53 pages

data structure

The document contains multiple programs demonstrating various algorithms including linear search, binary search, sorting algorithms (bubble sort, insertion sort, selection sort, quick sort, merge sort), and linked list operations (singly and doubly linked lists). Each program includes an objective, source code, and expected output. The algorithms are implemented in C programming language and cover fundamental data structures and searching/sorting techniques.

Uploaded by

saumyasaini2630
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)
7 views53 pages

data structure

The document contains multiple programs demonstrating various algorithms including linear search, binary search, sorting algorithms (bubble sort, insertion sort, selection sort, quick sort, merge sort), and linked list operations (singly and doubly linked lists). Each program includes an objective, source code, and expected output. The algorithms are implemented in C programming language and cover fundamental data structures and searching/sorting techniques.

Uploaded by

saumyasaini2630
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/ 53

Program-1

Objective- Program to implement linear search Linear search-


In linear search we compare the search element with each element of the array one by one.
Initialise a variable count. If the element mathes , element found or if the element is not present in
the array, the value of count will remain zero and the program will return element not found.

Source code-
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int i,k,a[100],f=0,n;
printf("Enter the no of elements");
scanf("%d",&n);
printf("Enter array elements");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the element to search for");
scanf("%d",&k);
for(i=0;i<n;i++)
{
if(a[i]==k)
{
f=1;
printf("Element found at %d position",i+1);
break;
}}
if(f==0)
printf("Not Found");
getch();}

OUTPUT
program -2
Objective- Program to implement Binary search-
Binary search is a search algorithm that finds a item in a sorted list by repeatedly
dividing the list half until the item is found . It’s most common ways to search an
element in an array.
SOURCE CODE-
#include <stdio.h>
#include<conio.h>
Void binarySearch(int arr[], int size, int key)
{
int low = 0, high = size - 1, mid;
while (low <= high) {
mid = (low + high) / 2;
if (arr[mid] == key)
{
printf("Element found at index %d\n", mid);
return;
}
else if
(arr[mid] < key) {
low = mid + 1;
}
else {
high = mid - 1;
}
}
printf("Element not found in the array\n");
}

int main() {
int n, i, key;
printf("Enter number of elements in the array: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements in sorted order:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Enter the element to search: ");
scanf("%d", &key);
binarySearch(arr, n, key);return 0;
}
OutPut
PROGRAM-3
Objective- Program to implement Bubble sort .
Bubble sort is sorting method that arranges a list of numbers or other elements in
order by compering adjacent elements and swapping them if they are out of order.
The algorithm is named for the way the larger elements “bubble” up to the top of the
list.
SOURCE CODE-
#include <stdio.h>
#include <conio.h>
void main()
{
int array[10]; int n, i,j, swap;
printf("Enter size of array\n"); scanf("%d", &n);
if(n>10)
printf("invalid array ");
else
{
printf("Enter array elements\n", n); for (i = 0; i < n; i++)
scanf("%d", &array[i]);
for (i = 0 ; i < n - 1; i++)
{
for (j = 0 ;j < n - i - 1; i++)
{
if (array[j] > array[j+1])
{
swap = array[j];
array[j] = array[j+1];
array[j+1] = swap;
}}}}
printf("Sorted array in ascending order:\n");
for (i = 0; i < n; i++)
printf("%d\t", array[i]);
return 0;
}
OUTPUT
PROGRAM-4
Objective- Program to implement Insertion sort.
Insertion sort is a simple sorting algorithm that builds a sorted array (or list) one item at a time by
comparing each new element with those already sorted and inserting it into the correct position.
It is often compared to sorting playing cards in hand, where you take one card and place it where
it belongs among the previously sorted cards.

SOURCE CODE-
#include <stdio.h>
int main() {
int a[100],i,j,k,n;
printf("Enter the no. of element");
scanf("%d",&n);
printf("Enter array elements");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=1;i<n;i++)
{
k=a[i];
j=i-1;
while(j>=0&&a[j]>k)
{
a[j+1]=a[j];
j--;
}
a[j+1]=k;
}
printf("After sorting:");
for(i=0;i<n;i++)
printf("\t %d",a[i]);
return 0;
}

OUTPUT
PROGRAM-5
Objective- Program to implement selection sort.
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting
the smallest (or largest) element from the unsorted portion and swapping it with the first
unsorted element. This process continues until the entire array is sorted.

SOURCE CODE
#include <stdio.h>
int main() {
int a[100],i,j,temp,n;
printf("Enter the no. of element");
scanf("%d",&n);
printf("Enter array elements");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n-1;i++)
{
int min=i;
for(j=i+1;j<n;j++)
{
if(a[min]>a[j])
min=j;
}
if(i!=min)
{
temp=a[i];
a[i]=a[min];
a[min]=temp;
}
}
printf("After sorting:");
for(i=0;i<n;i++)
printf("\t %d",a[i]);
return 0;
}

OUTPUT
PROGRAM-6
Objective- Program to implement Quick sort.
Quicksort is a divide-and-conquer sorting algorithm known for its efficiency. It selects
a pivot element, partitions the array into elements smaller and larger than the pivot,
and recursively sorts these subarrays.

SOURCE CODE
#include <stdio.h>
int partition(int a[], int low, int high) {
int pivot = a[low];
int i = low + 1;
int j = high;
int temp;
do {
while (a[i] <= pivot && i <= high) {
i++;
}
while (a[j] > pivot) {
j--;
}
if (i < j) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
} while (i < j);
temp = a[low];
a[low] = a[j];
a[j] = temp;
return j;
}

void quicksort(int a[], int low, int high) {


if (low < high) {
int partitionIndex = partition(a, low, high);
quicksort(a, low, partitionIndex - 1);
quicksort(a, partitionIndex + 1, high);
}
}

int main() {
int n;

printf("Enter the number of elements: ");


scanf("%d", &n);

int arr[n];
printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

quicksort(arr, 0, n - 1);

printf("Sorted array:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");

return 0;
}
PROGRAM-7
Objective- Program to implement Merge sort.
Merge Sort is a stable, divide-and-conquer sorting algorithm. It splits the array into
smaller subarrays, recursively sorts them, and merges the sorted subarrays into a
single array. Known for its consistent O(nlogn) time complexity, it is highly efficient
for large datasets but requires additional memory for merging
SOURCE CODE
#include <stdio.h>
#define MAX 100
int b[MAX];
void merge(int a[], int low, int mid, int high) {
int i = low, j = mid + 1, k = low;
while (i <= mid && j <= high) {
if (a[i] <= a[j]) {
b[k] = a[i];
i++;
} else {
b[k] = a[j];
j++;
}
k++;
}
while (i <= mid) {
b[k] = a[i];
i++;
k++;
}
while (j <= high) {
b[k] = a[j];
j++;
k++;
}
for (k = low; k <= high; k++) {
a[k] = b[k];
}
}
void mergesort(int a[], int low, int high) {
if (low < high) {
int mid = (low + high) / 2;
mergesort(a, low, mid);
mergesort(a, mid + 1, high);
merge(a, low, mid, high);
}
}
int main() {
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
mergesort(arr, 0, n - 1);
printf("Sorted array:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");

return 0;
}
PROGRAM-8
Objective- Program to implement singly Linked List(create, insert,
delete, display) .
A singly linked list is a type of data structure that consists of a sequence of elements (nodes)
where each node points to the next node in the sequence. It is called "singly" linked because each
node only points to the next node, not to the previous one.
Source Code-
#include <stdio.h>
#include <stdlib.h>
struct node { int data; struct node *next; };
struct node *head = NULL; struct node *newNode;
void insertAtBeginning(int data)
{ newNode = (struct node*)malloc(sizeof(struct node));
newNode->data = data;
newNode->next = head;
head = newNode;
}
void insertAtEnd(int data)
{
newNode =(struct node*)malloc(sizeof(struct node));
newNode->data = data;
newNode->next = NULL;
if (head == NULL)
{
head = newNode;
}
else
{
struct node *temp = head;
while (temp->next != NULL)
{
temp = temp->next;
}
temp->next = newNode;
}}
void insertAtIndex(int data, int index)
{
if (index == 0)
{
insertAtBeginning(data);
return;
}
newNode = (struct node*)malloc(sizeof(struct node));
newNode->data = data;
struct node *temp = head;
for (int i = 0; temp != NULL && i < index - 1; i++)
{
temp = temp->next;
}
if (temp == NULL)
{
printf("Index out of range\n");
free(newNode);
return;
}
newNode->next = temp->next;
temp->next = newNode;
}
void deleteAtBeginning()
{
if (head == NULL)
{
printf("List is empty\n");
return;
}
struct node *temp = head;
head = head->next;
free(temp);
}
void deleteAtEnd()
{
if (head == NULL)
{
printf("List is empty\n");
return;
}
if (head->next == NULL)
{
free(head);
head = NULL;
return;
}
struct node *temp = head;
while (temp->next!= NULL)
{
temp = temp->next;
}
free(temp->next);
temp->next = NULL;
}
void deleteAtIndex(int index)
{
if (head == NULL)
{
printf("List is empty\n");
return;
}
struct node *temp = head;
if (index == 0)
{
head = temp->next;
free(temp);
return;
}
for (int i = 0; temp != NULL && i < index - 1; i++)
{
temp = temp->next;
}
if (temp == NULL || temp->next == NULL)
{
printf("Index out of range\n");
return;
}
struct node *next = temp->next->next;
free(temp->next);
temp->next = next;
}
void printList()
{ struct node *temp = head;
while (temp != NULL)
{
printf("%d \t ", temp->data);
temp = temp->next;
}}
void reverseList()
{
struct node *prev = NULL, *current = head, *next = NULL;
while (current != NULL)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
head = prev;
}
int main()
{
int choice, data, index, numElements, element;
printf("Enter the number of elements for the linked list: ");
scanf("%d", &numElements);
printf("Enter the elements: \n");
for (int i = 0; i < numElements; i++)
{
scanf("%d", &element);
insertAtEnd(element);
}
while (1)
{
printf("\nMenu\n");
printf("1. Insert at Beginning\n");
printf("2. Insert at End\n");
printf("3. Insert at Index\n");
printf("4. Delete at Beginning\n");
printf("5. Delete at End\n");
printf("6. Delete at Index\n");
printf("7. Print List\n");
printf("8. Reverse List\n");
printf("9. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice)
{
case 1:
printf("Enter data: ");
scanf("%d", &data);
insertAtBeginning(data);
break;
case 2:
printf("Enter data: ");
scanf("%d", &data);
insertAtEnd(data);
break;
case 3:
printf("Enter data: ");
scanf("%d", &data);
printf("Enter index: ");
scanf("%d", &index);
insertAtIndex(data, index);
break;
case 4:
deleteAtBeginning();
break;
case 5:
deleteAtEnd();
break;
case 6:
printf("Enter index: ");
scanf("%d", &index);
deleteAtIndex(index);
break;
case 7:
printList();
break;
case 8:
reverseList();
break;
case 9:
exit(0);
break;
default:
printf("Invalid choice\n");
}}
return 0;
}

OUTPUT
PROGRAM-9
Objective- Program to implement doubly Linked List(create, insert,
delete, display) .
A doubly linked list is a data structure that consists of a set of nodes, each of which
contains a value and two pointers, one pointing to the previous node in the list and
one pointing to the next node in the list.

SOURCE CODE
#include <stdio.h>
#include<stdlib.h>
struct node{
int info;
struct node *prev,*next;
};
struct node *start=NULL;
struct node *q,*p,*temp;
int i;
void creatshell(int val){
temp=(struct node *)malloc(sizeof(struct node));
temp->info=val;
temp->next=NULL;
temp->prev=NULL;
}

void insert_at_beg(int value){


creatshell(value);
start->prev=temp;
temp->next=start;
start=temp;
}
void insert_at_end(int value){
creatshell(value);
q=start;
while(q->next!=NULL){
q=q->next;
}
q->next=temp;
temp->prev=q;
}
void print(){
q=start;
while(q!=NULL){
printf("%d\t",q->info);
q=q->next;
}
}
void insert_at_pos(int value , int pos){
creatshell(value);
q=start;
for(i=0;i<pos-1;i++){
p=q;
q=q->next;
}
temp->prev=p;
temp->next=q;
q->prev=temp;
p->next=temp;

}
void delet_at_beg(){
q=start;
start=start->next;
start->prev=NULL;
}
void delet_at_end(){
struct node *q,*start;
q=start;
while(q->next!=NULL){
q=q->next;
}
q=q->prev;
q->next =NULL;
}
void delet_at_pos(int pos){
q=start;
for(i=0;i<pos-1;i++){
p=q;
q=q->next;
}
q=q->next;
p->next=q;
q->prev=p;
}
void create_list()
{int n;
printf("How many nodes you want to create: ");
scanf("%d", &n);

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


{
temp = (struct node*)malloc(sizeof(struct node));
if (temp == NULL)
{
printf("Memory allocation failed\n");
}
printf("Enter the element in node %d: ", i + 1);
scanf("%d", &temp->info);
temp->next = NULL;

if (start == NULL)
{
start = temp;
} else
{
q->next = temp;
}
q = temp;
}}
int menu()
{
printf("\n1) To print the list:\n ");
printf("2) To insert at the beginning :\n");
printf("3) To insert at the end :\n");
printf("4) To insert at the position:\n");
printf("5) To delete from the beginning:\n");
printf("6) To delete from the end :\n");
printf("7) To delete from the position:\n");
printf("8) To Exit: ");

int item,choice,position;

scanf("%d",&choice);
switch (choice)
{
case 1 :
{
print();
menu();
break;
}
case 2:
{printf("enter the value you want to insert");
scanf("%d",&item);
insert_at_beg(item);
menu();
break;}
case 3:
{printf("enter the value you want to insert");
scanf("%d",&item);
insert_at_end(item);
menu();
break;}
case 4:
{printf("enter the value you want to insert");
scanf("%d",&item);
printf("enter the value you want to insert");
scanf("%d",&position);
insert_at_pos(item,position);
menu();
break;}
case 5: delet_at_beg();
menu();
break;
case 6: {delet_at_end();
menu();
break;}
case 7:printf("enter the value you want to insert");
scanf("%d",&position);
delet_at_pos(position);
menu();
break;
case 8: exit(0);
}
}

int main() {
create_list();
print();
menu();

}
OUTPUT
PROGRAM-10
Objective- Program to implement Stack using Array.
A stack using an array is a linear data structure that follows the Last In, First Out
(LIFO) principle. It uses an array for storage, with operations like push (add element)
and pop (remove element) performed at the top. Efficient for fixed-size collections, it
requires careful handling to avoid overflow.
SOURCE CODE
# include<stdio.h>
#include<stdlib.h>
struct node{
int info;
struct node *next;
};
struct node *q,*temp,*top=NULL;
int stack[50];
int n;
int push(int item)
{
temp=(struct node*)malloc(sizeof (struct node) );
temp->info=item;
temp->next=top;
top=temp;
}
int pop()
{
struct node *q;
if (top == NULL) {
printf("Stack Underflow! The stack is empty.\n");
return -1;
}
q = top;
printf("Popped: %d\n", top->info);
top = top->next;
free(q);
return 0;
}
int display()
{
q = top;
if (q == NULL) {
printf("Stack is empty\n");
return 0;
}
while (q != NULL) {
printf("%d ", q->info);
q = q->next;
}
printf("\n");
return 0;
}

int menu()
{
int ch, val;
printf("\n1) PUSH\n");
printf("2) POP\n");
printf("3) DISPLAY\n");
printf("Enter your choice: ");
scanf("%d", &ch);
switch (ch) {
case 1:
printf("Enter the value to insert: ");
scanf("%d", &val);
push(val);
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
exit(0);
break;
default:
printf("Invalid input\n");
break;
}
return 0;
}

int main()
{
printf("Enter the size of the stack: ");
scanf("%d", &n);
while (1) {
menu();
}
return 0;
}
PROGRAM-11
Objective- Program to implement Queue using Array.
A queue using an array is a linear data structure that follows the First In, First Out
(FIFO) principle. Elements are added at the rear (enqueue) and removed from the
front (dequeue). Efficient for fixed-size collections, it requires proper handling of front
and rear pointers to prevent overflow and underflow.
SOURCE CODE
#include <stdio.h>
int queue[50];
int n, front = -1, rear = -1;
void insert(int data)
{
if ((rear + 1) % n == front) {
printf("Queue is full\n");
return;
}
if (front == -1) {
front = 0;
}
rear = (rear + 1) % n;
queue[rear] = data;
printf("Inserted: %d\n", data);
}
void delete()
{
if (front == -1) {
printf("Queue is empty\n");
return;
}
printf("Deleted: %d\n", queue[front]);

if (front == rear) {
front = rear = -1;
} else {
front = (front + 1) % n;
}
}
void print()
{
if (front == -1) {
printf("Queue is empty\n");
return;
}
printf("Queue elements: ");
int i = front;
while (i != rear) {
printf("%d ", queue[i]);
i = (i + 1) % n;
}
printf("%d ", queue[rear]);
printf("\n");
}
int main()
{
int choice, data;
printf("Enter the size of the queue: ");
scanf("%d", &n);
while (1) {
printf("\n1) INSERT\n");
printf("2) DELETE\n");
printf("3) PRINT\n");
printf("4) EXIT\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter the data to insert: ");
scanf("%d", &data);
insert(data);
break;
case 2:
delete();
break;
case 3:
print();
break;
case 4:
return 0;
default:
printf("Invalid choice! Please try again.\n");
}
}
return 0;
}
PROGRAM-12
Objective- Program to implement Circular Queue using Array.
A Circular Queue connects the last position back to the first, allowing efficient space usage. When
the rear or front reaches the end of the array, it wraps around to the beginning. This circular
structure ensures continuous flow and maximizes available space.

SOURCE CODE
#include <stdio.h>
int queue[50];
int n, front = -1, rear = -1;
void insert(int data)
{
if ((rear + 1) % n == front)
{
printf("Queue is full\n");
return;
}
if (front == -1)
{
front = 0;
}
rear = (rear + 1) % n;
queue[rear] = data;
printf("Inserted: %d\n", data);
}
void delete()
{
if (front == -1)
{
printf("Queue is empty\n");
return;
}
printf("Deleted: %d\n", queue[front]);

if (front == rear)
{
front = rear = -1;
}
else
{
front = (front + 1) % n;
}
}
void print()
{
if (front == -1)
{
printf("Queue is empty\n");
return;
}
printf("Queue elements: ");
int i = front;
while (i != rear)
{
printf("%d ", queue[i]);
i = (i + 1) % n;
}
printf("%d ", queue[rear]);
printf("\n");
}
int main()
{
int choice, data;
printf("Enter the size of the queue: ");
scanf("%d", &n);
while (1)
{
printf("\n1) INSERT\n");
printf("2) DELETE\n");
printf("3) PRINT\n");
printf("4) EXIT\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice)
{
case 1:
printf("Enter the data to insert: ");
scanf("%d", &data);
insert(data);
break;
case 2:
delete();
break;
case 3:
print();
break;
case 4:
return 0;
default:
printf("Invalid choice! Please try again.\n");
}
}
return 0;
}
PROGRAM-13
Objective- Program to implement Stack using Linked List.
A stack is a linear data structure that operates on the Last In, First Out (LIFO)
principle, with key operations like push, pop, and peek performed at the top.
SOURCE CODE
# include<stdio.h>
#include<stdlib.h>
struct node{
int info;
struct node *next;
};
struct node *q,*temp,*top=NULL;
int stack[50];
int n;
int push(int item)
{
temp=(struct node*)malloc(sizeof (struct node) );
temp->info=item;
temp->next=top;
top=temp;
}
int pop()
{
struct node *q;
if (top == NULL) {
printf("Stack Underflow! The stack is empty.\n");
return -1;
}
q = top;
printf("Popped: %d\n", top->info);
top = top->next;
free(q);
return 0;
}
int display()
{
q = top;
if (q == NULL) {
printf("Stack is empty\n");
return 0;
}
while (q != NULL) {
printf("%d ", q->info);
q = q->next;
}
printf("\n");
return 0;
}
int menu()
{
int ch, val;
printf("\n1) PUSH\n");
printf("2) POP\n");
printf("3) DISPLAY\n");
printf("Enter your choice: ");
scanf("%d", &ch);
switch (ch) {
case 1:
printf("Enter the value to insert: ");
scanf("%d", &val);push(val);
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
exit(0);
break;
default:
printf("Invalid input\n");
break;
}
return 0;}
int main() {
printf("Enter the size of the stack: ");
scanf("%d", &n);
while (1) {
menu();
}
return 0;
}
PROGRAM-14
Objective- Program to implement Queue using Linked List.
A queue is a linear data structure that follows the First In, First Out (FIFO) principle.
Elements are added at the rear (enqueue) and removed from the front (dequeue).
SOURCE CODE
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* front = NULL;
struct Node* rear = NULL;
void insert(int data)
{
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Memory allocation failed.\n");
return;
}
newNode->data = data;
newNode->next = NULL;
if (rear == NULL) {
front = rear = newNode;
}
Else
{
rear->next = newNode;
rear = newNode;
}
printf("Inserted: %d\n", data);
}
void delete()
{
if (front == NULL)
{
printf("Queue is empty\n");
return;
}
struct Node* temp = front;
printf("Deleted: %d\n", front->data);
front = front->next;
if (front == NULL)
{
rear = NULL;
}
free(temp);
}
void print()
{
if (front == NULL) {
printf("Queue is empty\n");
return;
}
struct Node* temp = front;
printf("Queue elements: ");
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
int main()
{
int choice, data;
while (1)
{
printf("\n1) INSERT\n");
printf("2) DELETE\n");
printf("3) PRINT\n");
printf("4) EXIT\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter the data to insert: ");
scanf("%d", &data);
insert(data);
break;
case 2:
delete();
break;
case 3:
print();
break;
case 4:
return 0;
default:
printf("Invalid choice! Please try again.\n");
}
}

return 0;
}
PROGRAM-15
Objective- Program to implement Priority Queue using Linked List.
A priority queue is a specialized data structure where each element is associated
with a priority. Elements with higher priority are dequeued before lower-priority ones,
regardless of their insertion order. Implemented using heaps or other structures, it
supports operations like insertion, peek, and removal, often used in scheduling and
algorithms.

SOURCE CODE
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data, priority;
struct Node* next;
};
struct Node* front = NULL;
void enqueue(int value, int priority)
{
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->priority = priority;
newNode->next = NULL;
if (front == NULL || front->priority > priority) {
newNode->next = front;
front = newNode;
}
else
{
struct Node* temp = front;
while (temp->next != NULL && temp->next->priority <= priority)
{
temp = temp->next;
}
newNode->next = temp->next;
temp->next = newNode;
}
printf("%d with priority %d enqueued to the queue\n", value, priority);
}
void dequeue()
{
if (front == NULL)
{
printf("Queue Underflow\n");
return;
}
struct Node* temp = front;
printf("%d with priority %d dequeued from the queue\n", front->data, front->priority);
front = front->next;
free(temp);
}
void display()
{
if (front == NULL) {
printf("Queue is empty\n");
return;
}
struct Node* temp = front;
printf("Queue elements are:\n");
while (temp != NULL)
{
printf("Value: %d, Priority: %d\n", temp->data, temp->priority);
temp = temp->next;
}
}
int main()
{
int choice, value, priority;
while (1) {
printf("\n1. Enqueue\n2. Dequeue\n3. Display\n4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter the value to be enqueued: ");
scanf("%d", &value);
printf("Enter the priority: ");
scanf("%d", &priority);
enqueue(value, priority);
break;
case 2:
dequeue();
break;
case 3:
display();
break;
case 4:
return 0;
default:
printf("Invalid choice\n");
}
}
return 0;
}
PROGRAM-16
Objective- Program to implement solution of Tower of Hanoi problem
using recursion.
The Tower of Hanoi is a mathematical puzzle involving three rods and several disks
of different sizes. The goal is to move all disks from one rod to another, following
rules of only one disk move and size order.

SOURCE CODE
#include <stdio.h>
void tower(int n, char A, char B, char C)
{
if(n==1)
{
printf("%c to %c \n",A,B);
return;
}
tower(n-1,A,C,B);
printf("%c to %c\n",A,B);
tower (n-1,B,A,C);
}
int main()
{
int n;
printf("Enter the number of disks: ");
scanf("%d", &n);
tower (n, 'A', 'B', 'C');
return 0;
}

PROGRAM-17
Objective- Program to implement modulo division hash function using
Linear probing for collision resolution.
A modulo division hash function maps keys using h(k)=kmod mh(k) = k \mod
mh(k)=kmodm, where mmm is the table size. Linear probing resolves collisions by
sequentially checking subsequent slots, (h(k)+i)mod m(h(k) + i) \mod m(h(k)
+i)modm, until an empty slot is found.
SOURCE CODE
#include <stdio.h>
int hashFunction(int key)
{
return key % 10;
}
void insert(int table[], int key) {
int index = hashFunction(key);
int i = 0;
while (table[(index + i) % 10] != -1) {
i++;
}
table[(index + i) % 10] = key;
}
void display(int table[]) {
printf("\nHashtable is:\n");
for (int i = 0; i < 10; i++) {
if (table[i] != -1) {
printf("\n%d -> %d\n", i, table[i]);
} else {
printf("\n%d\n", i);
}
}
}
int main()
{
int hashTable[10], key, n;
for (int i = 0; i < 10; i++) {
hashTable[i] = -1;
}
printf("Enter size of data [0-10]:");
scanf("%d", &n);
printf("Enter the elements for table:");
for(int i = 0; i<n ; i++){
scanf("%d", &key);
insert(hashTable, key);
}
display(hashTable);
return 0;
}

PROGRAM-18
Objective- Program to construct Binary Search Tree, traverse it using
inorder, preorder, postorder traversal, find the largest and smallest node,
and count total number of nodes.
A Binary Search Tree (BST) is a hierarchical data structure where each node has at
most two children. For every node, the left child contains values smaller than the
node, and the right child contains larger values.
SOURCE CODE
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
struct Node* root = NULL;
struct Node* createNode(int data)
{
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
struct Node* insertNode(struct Node* node, int data)
{
if (node == NULL)
return createNode(data);
if (data < node->data)
node->left = insertNode(node->left, data);
else
node->right = insertNode(node->right, data);
return node;
}
void inorderTraversal(struct Node* node)
{
if (node != NULL) {
inorderTraversal(node->left);
printf("%d ", node->data);
inorderTraversal(node->right);
}
}
void preorderTraversal(struct Node* node)
{
if (node != NULL) {
printf("%d ", node->data);
preorderTraversal(node->left);
preorderTraversal(node->right);
}
}
void postorderTraversal(struct Node* node)
{
if (node != NULL) {
postorderTraversal(node->left);
postorderTraversal(node->right);
printf("%d ", node->data);
}
}
struct Node* findMin(struct Node* node)
{
while (node->left != NULL)
node = node->left;
return node;
}
struct Node* findMax(struct Node* node)
{
while (node->right != NULL)
node = node->right;
return node;
}
int countNodes(struct Node* node)
{
if (node == NULL)
return 0;
return 1 + countNodes(node->left) + countNodes(node->right);
}
int main()
{
int n, data;
printf("Enter the size of data:");
scanf("%d",&n);
printf("Enter the data:\n");
for (int i = 0; i < n; i++){
scanf("%d", &data);
root = insertNode(root, data);
}
printf("Inorder traversal: ");
inorderTraversal(root);
printf("\nPreorder traversal: ");
preorderTraversal(root);
printf("\nPostorder traversal: ");
postorderTraversal(root);
struct Node* minNode = findMin(root);
struct Node* maxNode = findMax(root);
printf("\nSmallest node: %d", minNode->data);
printf("\nLargest node: %d", maxNode->data);
int totalNodes = countNodes(root);
printf("\nTotal number of nodes: %d\n", totalNodes);
return 0;
}
PROGRAM-19
Objective- Program to implement BFS(Breadth First Search) Graph traversal
algorithm.
Breadth-First Search (BFS) is an algorithm for traversing or searching tree or graph data
structures. It starts at a selected node and explores all its neighboring nodes level by level,
utilizing a queue to manage the process. BFS ensures that the shortest path (minimal number of
edges) to each node is found and is particularly useful for finding the shortest path in
unweighted graphs.
SOURCE CODE
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define MAX 100
int graph[MAX][MAX];
int n;
void BFS_MST(int start)
{
int visited[MAX] = {0};
int queue[MAX];
int front = 0, rear = 0;
queue[rear++] = start;
visited[start] = 1;
printf("Edges in the Minimum Spanning Tree:\n");
while (front < rear)
{
int u = queue[front++];
for (int v = 0; v < n; v++)
{
if (graph[u][v] != 0 && !visited[v])
{
visited[v] = 1;
queue[rear++] = v;
printf("(%d, %d) - Weight: %d\n", u, v, graph[u][v]);
}}
}}
int main()
{
int start;
printf("Enter the number of vertices: ");
scanf("%d", &n);
printf("Enter the adjacency matrix:\n");
for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++)
{
scanf("%d", &graph[i][j]);
}}
printf("Enter the starting vertex: ");
scanf("%d", &start); BFS_MST(start);
return 0;
}
Output
PROGRAM-20
Objective- :- Program to implement kuruskal’s algorithm to find minimum
spanning tree of a given graph .
Kruskal's Algorithm is a popular method for finding the Minimum Spanning Tree
(MST) of a graph. It works by sorting all the edges in the graph by their weight and
adding them one by one to the MST, ensuring no cycles are formed. The algorithm
uses the Union-Find data structure to efficiently check and merge sets of vertices.
Kruskal's Algorithm is particularly effective for sparse graphs and ensures the
minimal total edge weight in the MST.
SOURCE CODE
#include <stdio.h>
#include <stdlib.h>
{
int src, dest, weight;
};
{
int parent, rank;
};
int find(struct Subset subsets[], int i)
{
if (subsets[i].parent != i) subsets[i].parent = find(subsets, subsets[i].parent);
return subsets[i].parent;
}
void Union(struct Subset subsets[], int x, int y)
{
int rootX = find(subsets, x);
int rootY = find(subsets, y);
if (subsets[rootX].rank < subsets[rootY].rank) subsets[rootX].parent = rootY;
else if (subsets[rootX].rank > subsets[rootY].rank) subsets[rootY].parent = rootX;
else { subsets[rootY].parent = rootX; subsets[rootX].rank++;
}
}
int compare(const void* a, const void* b)
{
struct Edge* a1 = (struct Edge*)a; struct Edge* b1 = (struct Edge*)b; return a1->weight > b1-
>weight;
}
void KruskalMST(struct Edge edges[], int V, int E) { struct Edge result[V];
int e = 0;
int i = 0;
qsort(edges, E, sizeof(edges[0]), compare);
struct Subset* subsets = (struct Subset*) malloc(V * sizeof(struct Subset));
for (int v = 0; v < V; ++v) { subsets[v].parent = v; subsets[v].rank = 0;
}
while (e < V - 1 && i < E) {
struct Edge next_edge = edges[i++];
int x = find(subsets, next_edge.src); int y = find(subsets, next_edge.dest);
if (x != y) {
result[e++] = next_edge;
Union(subsets, x, y);
}
}
printf("Edges in the Minimum Spanning Tree:\n");
for (i = 0; i < e; ++i)
printf("(%d, %d) - Weight: %d\n", result[i].src, result[i].dest, result[i].weight); free(subsets);
}
int main()
{
int V, E;
printf("Enter the number of vertices: ");
scanf("%d", &V);
printf("Enter the number of edges: ");
scanf("%d", &E);
struct Edge edges[E];
printf("Enter the edges (src dest weight):\n");
for (int i = 0; i < E; i++) {
scanf("%d %d %d", &edges[i].src, &edges[i].dest, &edges[i].weight);
}
KruskalMST(edges, V, E);
return 0;
}
Output

PROGRAM-21
Objective- :- Program to implement warshall’s algorithm to find all pair
shortest path of a graph.
Warshall's Algorithm, also known as the Floyd-Warshall Algorithm, is used to find the
shortest paths between all pairs of vertices in a weighted graph. It iteratively updates
the shortest paths by considering each vertex as an intermediate point. Warshall's
Algorithm is particularly useful for dense graphs and has a time complexity of
O(V3)O(V^3), where VV is the number of vertices. This algorithm ensures that the
shortest distance between any two vertices is accurately computed
Source code:-
#include <stdio.h>
#define INF 99999
#define MAX 100
matrix void printSolution(int dist[][MAX], int V)
{
printf("The following matrix shows the shortest distances between every pair of
vertices:\n");
for (int i = 0; i < V; i++)
{
for (int j = 0; j < V; j++)
{
if (dist[i][j] == INF)
printf("%7s", "INF");
else printf("%7d", dist[i][j]);
}
printf("\n");
}}
void floydWarshall(int graph[][MAX], int V)
{
int dist[MAX][MAX], i, j, k;
for (i = 0; i < V; i++)
for (j = 0; j < V; j++)
dist[i][j] = graph[i][j];
for (k = 0; k < V; k++) {
for (i = 0; i < V; i++) {
for (j = 0; j < V; j++) {
if (dist[i][k] + dist[k][j] < dist[i][j]) dist[i][j] = dist[i][k] + dist[k][j];
}}}
matrix printSolution(dist, V);
}
int main()
{
int V, graph[MAX][MAX];
printf("Enter the number of vertices: ");
scanf("%d", &V);
printf("Enter the adjacency matrix (use %d for INF):\n", INF);
for (int i = 0; i < V; i++)
{
for (int j = 0; j < V; j++)
{
scanf("%d", &graph[i][j]);
}}
floydWarshall(graph, V);
return 0;
}

Output

You might also like