DSA Lab File
DSA Lab File
DSA Lab File
UNIVERSITY
LAB FILE
Session: 2023-2024
`
10
LAB – 1
Aim: Write a program to implement basic operations on array.
1. Insertion 2. Deletion 3. Traversal
Insertion :
#include <stdio.h>
void main(){
int LA[] = {1,3,5,7,8};
int k = 3, n = 5, item = 10;
int i, j;
printf("The original array elements are :\n");
for(i = 0; i<n; i++) {
printf("LA[%d] = %d \n", i, LA[i]);
}
LA[k-1] = item;
printf("The array elements after updation :\n");
for(i = 0; i<n; i++) {
printf("LA[%d] = %d \n", i, LA[i]);
}
}
Output :
Array Before Insertion:
LA[0] = 0
LA[1] = 0
LA[2] = 0
Inserting Elements..
The array elements after insertion :
LA[0] = 2
LA[1] = 3
LA[2] = 4
Deletion :
#include <stdio.h>
void main(){
int LA[] = {1,3,5};
int n = 3;
int i;
printf("The original array elements are :\n");
for(i = 0; i<n; i++)
printf("LA[%d] = %d \n", i, LA[i]);
for(i = 1; i<n; i++) {
LA[i] = LA[i+1];
n = n - 1;
}
printf("The array elements after deletion :\n");
for(i = 0; i<n; i++)
printf("LA[%d] = %d \n", i, LA[i]);
}
Output:
The original array elements are :
LA[0] = 1
LA[1] = 3
LA[2] = 5
The array elements after deletion :
LA[0] = 1
LA[1] = 5
Transversal:
#include <stdio.h>
int main(){
int LA[] = {1,3,5,7,8};
int item = 10, k = 3, n = 5;
int i = 0, j = n;
printf("The original array elements are :\n");
for(i = 0; i<n; i++) {
printf("LA[%d] = %d \n", i, LA[i]);
}
}
Output:
The original array elements are :
LA[0] = 1
LA[1] = 3
LA[2] = 5
LA[3] = 7
LA[4] = 8
LAB – 2
Aim : Write a program that implements the following sorting methods to sort a
given list of integers in ascending order
i) Bubble sort ii)Selection sort iii)Insertion sort
i)Bubble sort:
#include<stdio.h>int main()
{
int array[100], n, c, d, swap; printf("Enternumberofelements\n"); scanf("%d",
&n);
printf("Enter%dintegers\n",n); for (c = 0; c <n; c++)
scanf("%d",&array[c]);for(c=0;c<n-1;c++)
{
for(d=0;d<n-c-1;d++)
{
if(array[d]>array[d+1])/*Fordecreasingorderuse<*/
{
swap =array[d];
array[d] =array[d+1]; array[d+1] = swap;
}
}
}
printf("Sortedlistinascendingorder:\n"); for (c = 0; c <n; c++)
printf("%d\n",array[c]); return 0;
}
SampleOutput:
Enter no of elements:5
Enter 5 numbers:34532035333
Sorted array is:32035333345
ii)Selectionsort:
#include<stdio.h>
intmain()
{
intarray[100], n,c,d, position,swap;
printf("Enternumberofelements\n"); scanf("%d", &n);
printf("Enter%dintegers\n",n);
for (c = 0; c <n; c++) scanf("%d",&array[c]);
for(c=0;c<(n-1);c++)
{
position =c;
for(d=c+1;d<n;d++)
{
if(array[position]>array[d]) position = d;
}
if(position!=c)
{
swap=array[c];
array[c]=array[position]; array[position] = swap;
}
}
printf("Sortedlistinascendingorder:\n");
for (c = 0; c <n; c++) printf("%d\n",array[c]);
return0;
}
Output:
Enterno:ofelements:5
Enter 5 numbers :34 13 204 355333
Sorted array is :13 34 204 333355
iii)Insertion sort:
#include<stdio.h>
intmain()
{
int n,array[1000],c,d,t;
printf("Enter number of elements\n"); scanf("%d", &n)
printf("Enter%dintegers\n",n);
for (c = 0; c <n; c++) scanf("%d",&array[c])
for(c=1;c<=n-1;c++){ d = c;
while(d>0&&array[d-1]>array[d]){ t = array[d];
array[d] =array[d-1]; array[d-1] = t;
d--;
}
}
printf("Sortedlistinascendingorder:\n");
for(c=0;c<=n-1;c++){ printf("%d\n", array[c]);
}
return0;
}
Output:
Enter elements to be sorted:8249361 sorted elements:
1234689
LAB -3
Aim : Write a C program to perform various operations such as creation,
insertion, deletion, search and display on single linked list.
Aim : Represent the given sparse matrix using array and linked list
}
else
{
while (temp->next != NULL)
temp = temp->next;
}
}
// This function prints contents of linked list
// starting from start
void PrintList(struct Node* start)
{
struct Node *temp, *r, *s;
temp = r = s = start;
printf("row_position: ");
while(temp != NULL)
{
printf("column_postion: ");
while(r != NULL)
{
printf("%d ", r->column_postion);
r = r->next;
}
printf("\n");
printf("Value: ");
while(s != NULL)
{
printf("%d ", s->value);
s = s->next;
}
printf("\n");
}
PrintList(start);
return 0;
}
OUTPUT:
row_position:0 0 1 1 3 3
column_position:2 4 2 3 1 2
Value:3 4 5 7 2 6
LAB-5
Aim: Write a program that uses functions to perform the following operations
on doubly linked list:
i)Creation ii)Insertion iii)Deletion iv)Traversal
#include<stdio.h>
#include<stdlib.h>
structnode
{
structnode*prev;
intn;
structnode*next;
}*h,*temp,*temp1,*temp2,*temp4;
voidinsert1();
voidinsert2();
voidinsert3();
voidtraversebeg();
voidtraverseend(int);
voidsort();
voidsearch();
voidupdate();
voiddelete();
intcount=0;
voidmain()
{
intch;
h = NULL;
temp=temp1=NULL;
printf("\n1-Insertat beginning");
printf("\n2-Insertat end");
printf("\n3-Insertatposition i");
printf("\n4-Deleteati");
printf("\n5-Displayfrombeginning");
printf("\n6-Displayfromend");
printf("\n7-Searchforelement");
printf("\n8-Sortthe list");
printf("\n9-Updatean element");
printf("\n10-Exit");
20
while(1)
{
printf("\nEnterchoice:"); scanf("%d", &ch);
switch(ch)
{
case1:
insert1();
break; case 2:
insert2();
break; case 3:
insert3();
break; case 4:
delete();
break; case 5:
traversebeg();
break; case 6:
temp2=h;
if(temp2==NULL)
printf("\nError:Listemptytodisplay"); else
{
printf("\nReverseorderoflinkedlistis:"); traverseend(temp2->n);
}
break; case 7:
search();
break; case 8:
sort();
break; case 9:
update();
break; case 10:
exit(0); default:
printf("\nWrongchoicemenu");
}
}
}
/*TOcreateanemptynode*/
voidcreate()
{
intdata;
temp=(structnode*)malloc(1*sizeof(structnode)); temp->prev = NULL;
temp->next=NULL;
printf("\nEntervaluetonode:"); scanf("%d", &data);
temp->n=data; count++;
}
/*TOinsertatbeginning*/
voidinsert1()
{
if(h==NULL)
{
create(); h = temp; temp1=h;
}
else
{
create();
temp->next=h; h->prev=temp; h = temp;
}
}
/*Toinsertatend*/
voidinsert2()
{
if(h==NULL)
{
create(); h = temp; temp1=h;
}
else
{
create();
temp1->next=temp; temp->prev=temp1; temp1 = temp;
}
}
/*Toinsertatanyposition*/
voidinsert3()
{
intpos,i=2;
printf("\nEnterpositiontobeinserted:"); scanf("%d", &pos);
temp2=h;
if((pos<1)||(pos>=count+1))
{
printf("\nPositionoutofrangetoinsert"); return;
}
if((h==NULL)&&(pos!=1))
{
printf("\nEmptylistcannotinsertotherthan1stposition"); return;
}
if((h==NULL)&&(pos==1))
{
create(); h = temp; temp1=h; return;
}
else
{
while(i<pos)
{
temp2=temp2->next; i++;
}
create();
temp->prev=temp2;
temp->next=temp2->next; temp2->next->prev=temp; temp2->next = temp;
}
}
/*Todeleteanelement*/
voiddelete()
{
inti=1, pos;
printf("\nEnterpositiontobedeleted:"); scanf("%d", &pos);
temp2=h;
if((pos<1)||(pos>=count+1))
{
printf("\nError:Positionoutofrangetodelete"); return;
}
if(h==NULL)
{
printf("\nError:Emptylistnoelementstodelete"); return;
}
else
{
while(i<pos)
{
temp2=temp2->next; i++;
}
if(i==1)
{
if(temp2->next==NULL)
{
printf("Nodedeletedfromlist"); free(temp2);
temp2=h=NULL; return;
}
}
if(temp2->next==NULL)
{
temp2->prev->next=NULL; free(temp2);
printf("Nodedeletedfromlist"); return;
}
temp2->next->prev=temp2->prev; if (i != 1)
temp2->prev->next=temp2->next;
/*Mightnotneedthisstatementifi==1check*/
if(i==1)
h = temp2->next; printf("\nNodedeleted"); free(temp2);
}
count--;
}
/*Traversefrombeginning*/
voidtraversebeg()
{
temp2=h;
if(temp2==NULL)
{
printf("Listemptytodisplay\n"); return;
}
printf("\nLinkedlistelementsfrombegining:");
while(temp2->next!=NULL)
{
printf("%d",temp2->n); temp2 = temp2->next;
}
printf("%d",temp2->n);
}
/*Totraversefromendrecursively*/
voidtraverseend(inti)
{
if(temp2!=NULL)
{
i=temp2->n;
temp2=temp2->next; traverseend(i); printf(" %d ", i);
}
}
/*Tosearchforanelementinthelist*/
voidsearch()
{
intdata,count=0; temp2 = h;
if(temp2==NULL)
{
printf("\nError:Listemptytosearchfordata"); return;
}
printf("\nEntervaluetosearch:"); scanf("%d", &data);
while(temp2!=NULL)
{
if(temp2->n==data)
{
}
else
}
printf("\nDatafoundin%dposition",count+1); return;
temp2=temp2->next; count++;
printf("\nError:%dnotfoundinlist",data);
}
/*Toupdateanodevalueinthelist*/
voidupdate()
{
intdata,data1;
printf("\nEnternodedatatobeupdated:"); scanf("%d", &data);
printf("\nEnternewdata:"); scanf("%d", &data1);
temp2=h;
if(temp2==NULL)
{
printf("\nError:Listemptynonodetoupdate"); return;
}
while(temp2!=NULL)
{
if(temp2->n==data)
{
}
else
}
temp2->n=data1; traversebeg(); return;
temp2=temp2->next;
printf("\nError:%dnotfoundinlisttoupdate",data);
}
/*Tosortthelinkedlist*/
voidsort()
{
inti,j,x;
temp2=h; temp4=h;
if(temp2==NULL)
{
printf("\nListemptytosort"); return;
}
for(temp2=h;temp2!=NULL;temp2=temp2->next)
{
for(temp4=temp2->next;temp4!=NULL;temp4=temp4->next)
{
if(temp2->n>temp4->n)
{
x=temp2->n;
temp2->n=temp4->n; temp4->n = x;
}
}
traversebeg();
}
Output:
1 -Insertatbeginning
2 -Insertatend
3 -Insertatpositioni
4 -Deleteati
5 -Displayfrombeginning
6 -Displayfromend
7 -Searchforelement
8 -Sortthelist
9 -Updateanelement
10 - Exit
Enterchoice:1
Entervaluetonode:10 Enter choice : 2
Entervaluetonode:50 Enter choice : 4
Enterpositiontobedeleted:1
Node deleted Enterchoice:1
Entervaluetonode:34 Enter choice : 3
Enterpositiontobeinserted:2 Enter value to node : 13
Enterchoice:4
Enterpositiontobedeleted:4
Error:Positionoutofrangetodelete Enter choice : 1
Entervaluetonode:15 Enter choice : 1
Entervaluetonode:67 Enter choice : 3
Enterpositiontobeinserted:2 Enter value to node : 34
Enterchoice:4
Enterpositiontobedeleted:3 Node deleted
Enterchoice:7
Entervaluetosearch:15
Error:15notfoundinlist Enter choice : 8
Linkedlistelementsfrombegining:1334345067 Enter choice : 9
Enternodedatatobeupdated:45 Enter new data : 89
Error:45notfoundinlisttoupdate Enter choice : 9
Enternodedatatobeupdated:50 Enter new data : 90
Enterchoice:5
Linkedlistelementsfrombegining : 13 34 34 90 67
Enterchoice:6
Reverseorderoflinkedlistis: Enter choice : 7 67 90 34 34 13
Entervaluetosearch:90
Datafoundin4position Enter choice : 8
Linkedlistelementsfrombegining Enter choice : 7 : 13 34 34 67
90
Entervaluetosearch:90
Datafoundin5position Enter choice : 9
Enternodedatatobeupdated:34 Enter new data : 56
Linked list elements from begining:1356346790 Enter choice : 10
LAB-6
Aim: Write a program that implement stack (its operations) using arrays:
/*Endofpush*/
/*Beginofpop*/
voidpop()
{
if(top==-1)
printf("StackUnderflow\n");
else
{
printf("Poppedelementis:%d\n",stack_arr[top]); top=top-1;
/*Endof pop*/
/*Beginofdisplay*/
voiddisplay()
{
inti;
if(top==-1)
printf("Stackisempty\n");
else
{
}
}
printf("Stackelements:\n");
for(i=top;i>=0;i--)
printf("%d\n",stack_arr[i]);
/*Endofdisplay*/
/*Beginofmain*/ main()
{
intchoice;
do{
printf("1.Push\n");
printf("2.Pop\n"); printf("3.Display\n"); printf("4.Quit\n");
printf("Enteryourchoice:"); scanf("%d",&choice); switch(choice)
{
case1:
push();
break;case 2:
pop();
break;case 3:
display();
break;case 4:
break;
default:
printf("Wrongchoice\n");
}}while(choice!=4);
}
/*Endofmain*/
SampleOutput:
STACKIMPLEMENTATIONPROGRAM
1. Push
2. Pop
3. Size
4. Exit
Enteryourchoice:2 Stack is empty.
STACKIMPLEMENTATIONPROGRAM
1. Push
2. Pop
3. Size
4. Exit
Enteryour choice: 1
Enterdatatopushintostack:10 Data pushed to stack.
STACKIMPLEMENTATIONPROGRAM
1. Push
2. Pop
3. Size
4. Exit
Enteryour choice: 1
Enterdatatopushintostack:20 Data pushed to stack.
STACKIMPLEMENTATIONPROGRAM
1. Push
2. Pop
3. Size
4. Exit
Enteryour choice: 1
Enterdatatopushintostack:30 Data pushed to stack.
STACKIMPLEMENTATIONPROGRAM
1. Push
2. Pop
3. Size
4. Exit
Enteryourchoice:3 Stack size: 3
STACKIMPLEMENTATIONPROGRAM
1. Push
2. Pop
3. Size
4. Exit
Enteryourchoice:2 Data => 3
STACKIMPLEMENTATIONPROGRAM
1. Push
2. Pop
3. Size
4. Exit
Enteryourchoice:2 Data => 20
STACKIMPLEMENTATIONPROGRAM
1. Push
2. Pop
3. Size
4. Exit
Enteryourchoice:2 Data => 10
STACKIMPLEMENTATIONPROGRAM
1. Push
2. Pop
3. Size
4. Exit
Enteryourchoice:2 Stack is empty.
STACKIMPLEMENTATIONPROGRAM
1. Push
2. Pop
3. Size
4. Exit
Enter your choice:4 Exiting from app.
LAB-7
Aim : Write a program that implement Queue (its operations) using Arrays :
// Key to be found
int key = 6;
// Searching in a BST
if (search(root, key) == NULL)
printf("%d not found\n", key);
else
printf("%d found\n", key);
key = 60;
// Searching in a BST
if (search(root, key) == NULL)
printf("%d not found\n", key);
else
printf("%d found\n", key);
return 0;
}
OUTPUT:
6 not found
60 found
LAB: 9
Aim: Sort the given list of number using heap sort and quick sort
// Heap Sort in C
#include <stdio.h>
// Function to swap the position of two elements
void swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
// To heapify a subtree rooted with node i
// which is an index in arr[].
// n is size of heap
void heapify(int arr[], int N, int i)
{
// Find largest among root,
// left child and right child
// Initialize largest as root
int largest = i;
// left = 2*i + 1
int left = 2 * i + 1;
// right = 2*i + 2
int right = 2 * i + 2;
// If left child is larger than root
if (left < N && arr[left] > arr[largest])
largest = left;
// If right child is larger than largest
// so far
if (right < N && arr[right] > arr[largest])
largest = right;
// Swap and continue heapifying
// if root is not largest
// If largest is not root
if (largest != i) {
swap(&arr[i], &arr[largest]);
// Recursively heapify the affected
// sub-tree
heapify(arr, N, largest);
}
}
// Main function to do heap sort
void heapSort(int arr[], int N)
{
// Build max heap
for (int i = N / 2 - 1; i >= 0; i--)
heapify(arr, N, i);
// Heap sort
for (int i = N - 1; i >= 0; i--) {
swap(&arr[0], &arr[i]);
heapify(arr, i, 0);
}
}
// A utility function to print array of size n
void printArray(int arr[], int N)
{
for (int i = 0; i < N; i++)
printf("%d ", arr[i]);
printf("\n");
}
// Driver's code
int main()
{
int arr[] = { 12, 11, 13, 5, 6, 7 };
int N = sizeof(arr) / sizeof(arr[0]);
// Function call
heapSort(arr, N);
printf("Sorted array is\n");
printArray(arr, N);
}
OUTPUT:
Sorted array is
5 6 7 11 12 13
LAB : 10
Aim: Implement Depth First Search and Breadth First Search
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX 5
void addVertex(char);
void addEdge(int,int );
void displayVertex(int);
void depthFirstSearch();
int getAdjUnvisitedVertex(int);
struct Vertex {
char label;
bool visited;
};
//stack variables
int stack[MAX];
int top = -1;
//graph variables
//array of vertices
struct Vertex* lstVertices[MAX];
//adjacency matrix
int adjMatrix[MAX][MAX];
//vertex count
int vertexCount = 0;
//stack functions
void push(int item) {
stack[++top] = item;
}
int pop() {
return stack[top--];
}
int peek() {
return stack[top];
}
bool isStackEmpty() {
return top == -1;
}
//graph functions
//add vertex to the vertex list
void addVertex(char label) {
struct Vertex* vertex = (struct Vertex*) malloc(sizeof(struct Vertex));
vertex->label = label;
vertex->visited = false;
lstVertices[vertexCount++] = vertex;
}
//add edge to edge array
void addEdge(int start,int end) {
adjMatrix[start][end] = 1;
adjMatrix[end][start] = 1;
}
//display the vertex
void displayVertex(int vertexIndex) {
printf("%c ",lstVertices[vertexIndex]->label);
}
//get the adjacent unvisited vertex
int getAdjUnvisitedVertex(int vertexIndex) {
int i;
for(i = 0; i < vertexCount; i++) {
if(adjMatrix[vertexIndex][i] == 1 && lstVertices[i]->visited == false) {
return i;
}
}
return -1;
}
void depthFirstSearch() {
int i;
//mark first node as visited
lstVertices[0]->visited = true;
//display the vertex
displayVertex(0);
//push vertex index in stack
push(0);
while(!isStackEmpty()) {
//get the unvisited vertex of vertex which is at top of the stack
int unvisitedVertex = getAdjUnvisitedVertex(peek());
//no adjacent vertex found
if(unvisitedVertex == -1) {
pop();
} else {
lstVertices[unvisitedVertex]->visited = true;
displayVertex(unvisitedVertex);
push(unvisitedVertex);
}
}
//stack is empty, search is complete, reset the visited flag
for(i = 0;i < vertexCount;i++) {
lstVertices[i]->visited = false;
}
}
int main() {
int i, j;
for(i = 0; i < MAX; i++) // set adjacency {
for(j = 0; j < MAX; j++) // matrix to 0
adjMatrix[i][j] = 0;
addVertex('S'); // 0
addVertex('A'); // 1
addVertex('B'); // 2
addVertex('C'); // 3
addVertex('D'); // 4
addEdge(0, 1); // S - A
addEdge(0, 2); // S - B
addEdge(0, 3); // S - C
addEdge(1, 4); // A - D
addEdge(2, 4); // B - D
addEdge(3, 4); // C - D
printf("Depth First Search: ");
depthFirstSearch();
return 0;
}
OUTPUT:
Depth First Search: S A D B C
OUTPUT:
Following is Breadth First Traversal (starting from vertex 2)
2031