You are on page 1of 65

GREATER NOIDA INSTITUTE OF

TECHNOLOGY

DATA STRUCTURE LAB


(KCS 351)
SESSION: 2021-2022

SUBMITTED BY: SUBMITTED TO:


NAME: Aayush Kumar
ROLL NO: 2001320100002 Ms. Suvidha Verma
B.Tech CSE
2ND Year- A
S.NO. NAME OF THE PROGRAM DATE REMARKS

1. C Program for Bubble Sort

2. C Program for Optimized Bubble Sort

3. C Program for Linear Search

4. C Program for Binary Search

5. C Program for Implementation of


Stack Using Array
6. C Program for Implementation of
Queue Using Array
7. C Program for Implementation of
Circular Queue Using Array
8. C Program for Implementation of
Stack Using Linked List
9. C Program for Implementation of
Queue Using Linked List
10. Graph Implementation Using
Adjaceny Matrix
11. Graph Traversal of BFS and DFS

12. Minimum Cost Spanning Tree by


Prim’s Algo
13. Implementation Of Tree Structure
Using Linked List
14. Tree Traversal Pre-order, Post-
order,In-order
INDEX
1.Write a program in C to Implement Bubble Sort
#include<stdio.h>
int main()
{
int count, temp, i, j, number[30];
printf("How many numbers are u going to enter?: ");
scanf("%d",&count);

printf("Enter %d numbers: ",count);


for(i=0;i<count;i++)
scanf("%d",&number[i]);
for(i=count-2;i>=0;i--)
{
for(j=0;j<=i;j++)
{
if(number[j]>number[j+1])
{
temp=number[j];
number[j]=number[j+1];
number[j+1]=temp;
}
}
}
printf("Sorted elements: ");
for(i=0;i<count;i++)
printf(" %d",number[i]);

return 0;
}

Output:
2. Write a program in C to Implement Optimized
Bubble Sort

#include <stdio.h>

void swap(int* x, int* y)


{
int temp = *x;
*x = *y;
*y = temp;
}

void bubble_sort(int arr[], int n)


{
int i, j,swapped;
for (i = 0; i < n - 1; i++)
{
swapped = 0;
for (j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
swap(&arr[j], &arr[j + 1]);
swapped = 1;
}
}
if (swapped == 0)
break;
}
}

int main()
{
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
printf("\nInput Array: \n");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);

bubble_sort(arr, n);
printf("\nSorted Array: \n");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}

Output:
3. Write a program in C to perform Linear Search

#include<stdio.h>
int main()
{

int A[20],n,i,item;

printf("Enter the number of elements n \n");


scanf("%d",&n);
printf("Enter the elements in array \n");
for(i=0;i<n;i++)
{
scanf("%d",&A[i]);
}
printf("Enter the value that we want to search\n");
scanf("%d",&item);
for(i=0;i<n;i++)
{
if(item==A[i])
{
printf("Item is found and search is successful at the location =%d\n",i+1);
break;

}
}
if(i==n)
{
printf("Item is not found and search is unsuccessful \n");
}
return 0;
}

Output:
4. Write a program in C to perform Binary Search

#include <stdio.h>
int main()
{
int i, low, high, mid, n, key, array[100];
printf("Enter number of elements\n");
scanf("%d",&n);
printf("Enter %d integers\n", n);
for(i = 0; i < n; i++)
scanf("%d",&array[i]);
printf("Enter value to find\n");
scanf("%d", &key);
low = 0;
high = n - 1;
mid = (low+high)/2;
while (low <= high)
{
if(array[mid] < key)
low = mid + 1;
else if (array[mid] == key)
{
printf("%d found at location %d\n", key, mid+1);
break;
}
else
high = mid - 1;
mid = (low + high)/2;
}
if(low > high)
printf("Not found! %d isn't present in the list\n", key);
return 0;
}

Output:
5. Write a Program in C to Implement Stack Using
Array

#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 and Maximum Size =100:");
scanf("%d",&n);
printf("\n\t STACK OPERATIONS USING ARRAY");
printf("\n\t--------------------------------");
printf("\n\t 1.PUSH\n\t 2.POP\n\t 3.DISPLAY\n\t 4.EXIT");
do
{
printf("\n Enter the Choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
push();
break;
}
case 2:
{
pop();
break;
}
case 3:
{
display();
break;
}
case 4:
{
printf("\n\t EXIT POINT ");
break;
}
default:
{
printf ("\n\t Please Enter a Valid Choice(1/2/3/4)");
}

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

}
else
{
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:
6. Write a Program in C to Implement Queue Using
Array
#include<stdio.h>
#include<stdlib.h>
#define maxsize 5
void enqueue();
void dequeue();
void display();
int front = -1, rear = -1;
int queue[maxsize];
void main ()
{
int choice;
while(choice != 4)
{
printf("\n***************MENU***************\n");
printf("\n=================================================================\n");
printf("\n1.insert\n2.Delete\n3.Display \n4.Exit\n");
printf("\nEnter your choice ?");
scanf("%d",&choice);
switch(choice)
{
case 1:
enqueue();
break;
case 2:
dequeue();
break;
case 3:
display();
break;
case 4:
exit(0);
break;
default:
printf("\nEnter valid choice??\n");
}
}
}
void enqueue()
{
int item;
printf("\nEnter the element\n");
scanf("\n%d",&item);
if(rear == maxsize-1)
{
printf("\nOVERFLOW\n");
return;
}
if(front == -1 && rear == -1)
{
front = 0;
rear = 0;
}
else
{
rear = rear+1;
}
queue[rear] = item;

}
void dequeue()
{
int item;
if (front == -1 || front > rear)
{
printf("\nUNDERFLOW\n");
return;

}
else
{
item = queue[front];
if(front == rear)
{
front = -1;
rear = -1 ;
}
else
{
front = front + 1;
}

void display()
{
int i;
if(rear == -1)
{
printf("\nEmpty queue\n");
}
else
{ printf("\nprinting values .....\n");
for(i=front;i<=rear;i++)
{
printf("\n%d\n",queue[i]);
}
}
}
Output:
7. Write a Program in C to Implement Circular Queue
Using Array

#include <stdio.h>
#define SIZE 5

int items[SIZE];
int front = -1, rear = -1;

int isFull() {
if ((front == rear + 1) || (front == 0 && rear == SIZE - 1)) return 1;
return 0;
}

int isEmpty() {
if (front == -1) return 1;
return 0;
}
void enQueue(int element)
{
if (isFull())
printf("\n Queue is full!! \n");
else {
if (front == -1) front = 0;
rear = (rear + 1) % SIZE;
items[rear] = element;
printf("\n Inserted -> %d", element);
}
}

int deQueue()
{
int element;
if (isEmpty())
{
printf("\n Queue is empty !! \n");
return (-1);
}
else
{
element = items[front];
if (front == rear) {
front = -1;
rear = -1;
}
else
{
front = (front + 1) % SIZE;
}
printf("\n Deleted element -> %d \n", element);
return (element);
}
}

void display()
{
int i;
if (isEmpty())
printf(" \n Empty Queue\n");
else
{
printf("\n Front -> %d ", front);
printf("\n Items -> ");
for (i = front; i != rear; i = (i + 1) % SIZE)
{
printf("%d ", items[i]);
}
printf("%d ", items[i]);
printf("\n Rear -> %d \n", rear);
}
}

int main() {
deQueue();

enQueue(1);
enQueue(2);
enQueue(3);
enQueue(4);
enQueue(5);

enQueue(6);

display();
deQueue();
display();
enQueue(7);
display();

enQueue(8);
return 0;
}
Output:
8. Write a program in C to Implement of Stack Using
Linked List

#include <stdio.h>
#include <stdlib.h>
void push();
void pop();
void display();
struct node
{
int val;
struct node *next;
};
struct node *head;

void main ()
{
int choice=0;
printf("\n*********Stack operations using linked list*********\n");
printf("\n----------------------------------------------\n");
while(choice != 4)
{
printf("\n\nChose one from the below options...\n");
printf("\n1.Push\n2.Pop\n3.Show\n4.Exit");
printf("\n Enter your choice \n");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
push();
break;
}
case 2:
{
pop();
break;
}
case 3:
{
display();
break;
}
case 4:
{
printf("Exiting....");
break;
}
default:
{
printf("Please Enter valid choice ");
}
};
}
}
void push ()
{
int val;
struct node *ptr = (struct node*)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("not able to push the element");
}
else
{
printf("Enter the value");
scanf("%d",&val);
if(head==NULL)
{
ptr->val = val;
ptr -> next = NULL;
head=ptr;
}
else
{
ptr->val = val;
ptr->next = head;
head=ptr;

}
printf("Item pushed");

}
}

void pop()
{
int item;
struct node *ptr;
if (head == NULL)
{
printf("Underflow");
}
else
{
item = head->val;
ptr = head;
head = head->next;
free(ptr);
printf("Item popped");
}
}
void display()
{
int i;
struct node *ptr;
ptr=head;
if(ptr == NULL)
{
printf("Stack is empty\n");
}
else
{
printf("Printing Stack elements \n");
while(ptr!=NULL)
{
printf("%d\n",ptr->val);
ptr = ptr->next;
}
}
}
Output:
9. Write a program in C to Implement of Queue Using
Linked List
#include<stdio.h>

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

struct Node *front = NULL,*rear = NULL;

void EnQueue(int);
void DeQueue();
void display();
void Front();
void QueueSize();
int main()
{
int choice, value;
printf("\n*** Queue Implementation using Linked List ***\n");
while(1)
{
printf("\n****** MENU ******\n");
printf("1. Insert in Queue\n");
printf("2. Delete From Queue\n");
printf("3. Display Queue\n");
printf("4. Front of the Queue\n");
printf("5. Size of Queue\n");
printf("6. Exit\n");

printf("Enter your choice: ");


scanf("%d",&choice);

switch(choice)
{
case 1:
printf("Insert the value you want to enter: ");
scanf("%d", &value);

EnQueue(value);
break;
case 2:
DeQueue();
break;
case 3:
display();
break;
case 4:
Front();
break;
case 5:
QueueSize();
break;
case 6:
exit(0);
default:
printf("\nInvalid Selection!!..Select valid number please!!\n");
};
}
return 0;
}

void EnQueue(int value)


{
struct Node *newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode -> data = value;
newNode -> next = NULL;

if(front == NULL)
front = rear = newNode;
else
{
rear -> next = newNode;
rear = newNode;
}
printf("\n Data inserted in Queue!!!\n");
}

void DeQueue()
{
if(front == NULL)
printf("\n Queue is Empty!!!\n");
else
{
struct Node *temp = front;
front = front -> next;
printf("\n Deleted element is: %d\n", temp->data);
free(temp);
}
}

void display()
{
if(front == NULL)
printf("\n Queue is Empty!!!\n");
else
{
struct Node *temp = front;
while(temp->next != NULL)
{
printf("%d --> ",temp->data);
temp = temp -> next;
}
printf("%d \n",temp->data);
}
}

void Front()
{
if(front==NULL)
printf("\n Queue is Empty!!!\n");
else
printf("\n Data at front of the queue is %d \n",front->data);
}

void QueueSize()
{
if(front==NULL)
printf("\n Queue is Empty!!!\n");
else
{
int count=0;
struct Node *temp = front;
while(temp->next != NULL)
{
count++;
temp = temp -> next;
}
printf("\n Size of the queue is %d \n",count+1);
}
}

Output:
10. Write a program in C to Implementation of Graph
Using Adjacency Matrix
#include<stdio.h>
#define max 20
int adj[max][max];
int n;
main() {
int choice;
int node, origin, destin;
create_graph();
while (1) {
printf("1.Insert a node\n");
printf("2.Delete a node\n");
printf("3.Dispaly\n");
printf("4.Exit\n");
printf("Enter your choice : ");
scanf("%d", &choice);
switch (choice) {
case 1:
insert_node();
break;
case 2:
printf("Enter a node to be deleted : ");
fflush(stdin);
scanf("%d", &node);
delete_node(node);
break;
case 3:
display();
break;
case 4:
exit(0);
default:
printf("Wrong choice\n");
break;
}
}

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

printf("Enter number of nodes : ");


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

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


{
printf("Enter edge %d( 0 0 ) to quit : ", i);
scanf("%d %d", &origin, &destin);
if ((origin == 0) && (destin == 0))
break;
if (origin > n || destin > n || origin <= 0 || destin <= 0) {
printf("Invalid edge!\n");
i--;
}
else
adj[origin][destin] = 1;
}
}

display()
{
int i, j;
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
printf("%4d", adj[i][j]);
printf("\n");
}
}
insert_node()
{
int i;
n++;
printf("The inserted node is %d \n", n);
for (i = 1; i <= n; i++)
{
adj[i][n] = 0;
adj[n][i] = 0;
}
}

void delete_node(char u)
{
int i, j;
if (n == 0) {
printf("Graph is empty\n");
return;
}
if (u > n)
{
printf("This node is not present in the graph\n");
return;
}
for (i = u; i <= n - 1; i++)
for (j = 1; j <= n; j++)
{
adj[j][i] = adj[j][i + 1];
adj[i][j] = adj[i + 1][j];
}
n--;
}

Output:
11.Write a program in C for Graph Traversal For BFS
and DFS

#include<stdio.h>

int q[20],top=-1,front=-1,rear=-1,a[20][20],vis[20],stack[20];
int delete();
void add(int item);
void bfs(int s,int n);
void dfs(int s,int n);
void push(int item);
int pop();

void main()
{
int n,i,s,ch,j;
char c,dummy;
printf("ENTER THE NUMBER VERTICES ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("ENTER 1 IF %d HAS A NODE WITH %d ELSE 0 ",i,j);
scanf("%d",&a[i][j]);
}
}
printf("THE ADJACENCY MATRIX IS\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf(" %d",a[i][j]);
}
printf("\n");
}

do
{
for(i=1;i<=n;i++)
vis[i]=0;
printf("\nMENU");
printf("\n1.B.F.S");
printf("\n2.D.F.S");
printf("\nENTER YOUR CHOICE");
scanf("%d",&ch);
printf("ENTER THE SOURCE VERTEX :");
scanf("%d",&s);

switch(ch)
{
case 1:bfs(s,n);
break;
case 2:
dfs(s,n);
break;
}
printf("DO U WANT TO CONTINUE(Y/N) ? ");
scanf("%c",&dummy);
scanf("%c",&c);
}while((c=='y')||(c=='Y'));
}

//**************BFS(breadth-first search) code**************//


void bfs(int s,int n)
{
int p,i;
add(s);
vis[s]=1;
p=delete();
if(p!=0)
printf(" %d",p);
while(p!=0)
{
for(i=1;i<=n;i++)
if((a[p][i]!=0)&&(vis[i]==0))
{
add(i);
vis[i]=1;
}
p=delete();
if(p!=0)
printf(" %d ",p);
}
for(i=1;i<=n;i++)
if(vis[i]==0)
bfs(i,n);
}

void add(int item)


{
if(rear==19)
printf("QUEUE FULL");
else
{
if(rear==-1)
{
q[++rear]=item;
front++;
}
else
q[++rear]=item;
}
}
int delete()
{
int k;
if((front>rear)||(front==-1))
return(0);
else
{
k=q[front++];
return(k);
}
}

//***************DFS(depth-first search) code******************//


void dfs(int s,int n)
{
int i,k;
push(s);
vis[s]=1;
k=pop();
if(k!=0)
printf(" %d ",k);
while(k!=0)
{
for(i=1;i<=n;i++)
if((a[k][i]!=0)&&(vis[i]==0))
{
push(i);
vis[i]=1;
}
k=pop();
if(k!=0)
printf(" %d ",k);
}
for(i=1;i<=n;i++)
if(vis[i]==0)
dfs(i,n);
}
void push(int item)
{
if(top==19)
printf("Stack overflow ");
else
stack[++top]=item;
}
int pop()
{
int k;
if(top==-1)
return(0);
else
{
k=stack[top--];
return(k);
}
}

Output:
12. Write a program in C to find Minimum Cost
Spanning tree By Prim’s Algo
#include<stdio.h>
#include<stdlib.h>

#define infinity 9999


#define MAX 20

int G[MAX][MAX],spanning[MAX][MAX],n;

int prims();

int main()
{
int i,j,total_cost;
printf("Enter no. of vertices:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
total_cost=prims();
printf("\nspanning tree matrix:\n");
for(i=0;i<n;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",spanning[i][j]);
}
printf("\n\nTotal cost of spanning tree=%d",total_cost);
return 0;
}

int prims()
{
int cost[MAX][MAX];
int u,v,min_distance,distance[MAX],from[MAX];
int visited[MAX],no_of_edges,i,min_cost,j;
//create cost[][] matrix,spanning[][]
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
if(G[i][j]==0)
cost[i][j]=infinity;
else
cost[i][j]=G[i][j];
spanning[i][j]=0;
}
//initialise visited[],distance[] and from[]
distance[0]=0;
visited[0]=1;
for(i=1;i<n;i++)
{
distance[i]=cost[0][i];
from[i]=0;
visited[i]=0;
}
min_cost=0; //cost of spanning tree
no_of_edges=n-1; //no. of edges to be added
while(no_of_edges>0)
{
//find the vertex at minimum distance from the tree
min_distance=infinity;
for(i=1;i<n;i++)
if(visited[i]==0&&distance[i]<min_distance)
{
v=i;
min_distance=distance[i];
}
u=from[v];
//insert the edge in spanning tree
spanning[u][v]=distance[v];
spanning[v][u]=distance[v];
no_of_edges--;
visited[v]=1;
//updated the distance[] array
for(i=1;i<n;i++)
if(visited[i]==0&&cost[i][v]<distance[i])
{
distance[i]=cost[i][v];
from[i]=v;
}
min_cost=min_cost+cost[u][v];
}
return(min_cost);
}

Output:
13. Write a program in C for Implementation of Tree
Structure Using Linked List
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

//Represent a node of binary tree


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

//Represent the root of binary tree


struct node *root = NULL;

//createNode() will create a new node


struct node* createNode(int data){
//Create a new node
struct node *newNode = (struct node*)malloc(sizeof(struct node));
//Assign data to newNode, set left and right child to NULL
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;

return newNode;
}

//Represent a queue
struct queue
{
int front, rear, size;
struct node* *arr;
};

//createQueue() will create a queue


struct queue* createQueue()
{
struct queue* newQueue = (struct queue*) malloc(sizeof( struct queue ));

newQueue->front = -1;
newQueue->rear = 0;
newQueue->size = 0;

newQueue->arr = (struct node**) malloc(100 * sizeof( struct node* ));

return newQueue;
}

//Adds a node to queue


void enqueue(struct queue* queue, struct node *temp){
queue->arr[queue->rear++] = temp;
queue->size++;
}

//Deletes a node from queue


struct node *dequeue(struct queue* queue){
queue->size--;
return queue->arr[++queue->front];
}
//insertNode() will add new node to the binary tree
void insertNode(int data) {
//Create a new node
struct node *newNode = createNode(data);
//Check whether tree is empty
if(root == NULL){
root = newNode;
return;
}
else {
//Queue will be used to keep track of nodes of tree level-wise
struct queue* queue = createQueue();
//Add root to the queue
enqueue(queue, root);

while(true)
{
struct node *node = dequeue(queue);
//If node has both left and right child, add both the child to queue
if(node->left != NULL && node->right != NULL)
{
enqueue(queue, node->left);
enqueue(queue, node->right);
}
else
{
//If node has no left child, make newNode as left child
if(node->left == NULL)
{
node->left = newNode;
enqueue(queue, node->left);
}
//If node has left child but no right child, make newNode as right child
else
{
node->right = newNode;
enqueue(queue, node->right);
}
break;
}
}
}
}

//inorder() will perform inorder traversal on binary search tree


void inorderTraversal(struct node *node) {
//Check whether tree is empty
if(root == NULL)
{
printf("Tree is empty\n");
return;
}
else
{

if(node->left != NULL)
inorderTraversal(node->left);
printf("%d ", node->data);
if(node->right != NULL)
inorderTraversal(node->right);

}
}

int main()
{

//Add nodes to the binary tree


insertNode(1);
//1 will become root node of the tree
printf("Binary tree after insertion: \n");
//Binary after inserting nodes
inorderTraversal(root);

insertNode(2);
insertNode(3);
//2 will become left child and 3 will become right child of root node 1
printf("\nBinary tree after insertion: \n");
//Binary after inserting nodes
inorderTraversal(root);

insertNode(4);
insertNode(5);
//4 will become left child and 5 will become right child of node 2
printf("\nBinary tree after insertion: \n");
//Binary after inserting nodes
inorderTraversal(root);

insertNode(6);
insertNode(7);
//6 will become left child and 7 will become right child of node 3
printf("\nBinary tree after insertion: \n");
//Binary after inserting nodes
inorderTraversal(root);

return 0;
}

Output:
14. Write a Program in C for Tree Traversal Pre-
Order, Post-Order,In-Order
#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);
}

// preorderTraversal traversal
void preorderTraversal(struct node* root) {
if (root == NULL) return;
printf("%d ->", root->item);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
// postorderTraversal traversal
void postorderTraversal(struct node* root) {
if (root == NULL) return;
postorderTraversal(root->left);
postorderTraversal(root->right);
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, 12);
insertRight(root, 9);

insertLeft(root->left, 5);
insertRight(root->left, 6);

printf("Inorder traversal \n");


inorderTraversal(root);

printf("\nPreorder traversal \n");


preorderTraversal(root);

printf("\nPostorder traversal \n");


postorderTraversal(root);
}

Output:

You might also like