Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

DSA Lab File

Download as pdf or txt
Download as pdf or txt
You are on page 1of 54

SHRI RAMSWAROOP MEMORIAL

UNIVERSITY

Data Structure & Algorithm Lab


(BCS 3513)

LAB FILE
Session: 2023-2024

SUBMITTED TO: SUBMITTED BY:


Ms. Atifa Parveen Name :
Mr. Shiv Hari Tiwari Roll No. :
Group : CS-
INDEX

S. No Name of Experiment Date Faculty Remarks


Signature

`
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.

#include<stdio.h> #include<conio.h> #include<alloc.h> #include<stdlib.h> void


create();
void insert(); void del(); void display(); struct node
{
int data;
struct node *link;
};
struct node *first = null, *last = null ,*next, *curr, *prev; int ch;
void main()
{
clrscr();
printf(“singly linked list \n”); do
{
printf(“\n 1.create \n 2.insert \n 3.delete \n 4.exit \n ”); printf(“Enter your
choice”);
scanf(“%d”, &ch); switch(ch)
{
case 1: create();
display(); break;
case 2: insert();
display(); break;
case 3: del();
display(); break;
case 4: exit(0);
}
}
while(ch<=3);
}
void create()
{
curr = (struct node *) malloc(sizeof(struct node));
printf(“Enter the data: ”); scanf(“%d”, &curr -> data); curr -> link = null;
first = curr; last = curr;
}
void insert()
{
int pos, c = 1;
curr=(struct node *)malloc(sizeof(struct node)); printf(“Enter the data:”);
scanf(“%d”, &curr -> data); printf(“Enter the position:”); scanf(“%d”, &pos);
if((pos == 1) && (first != null))
{
curr -> link = first; first = curr;
}
else
{
next = first; while(c < pos)
{
prev = next;
next = prev -> link; c++;
}
if(prev == null)
{
printf(“\n Invalid position”);
}
else
{
curr -> link = prev -> link; prev -> link = curr;
if(curr -> link == null)
{
last = curr;
}
}
void del()
{
int pos, c = 1;
printf(“Enter the position”); scanf(“%d”, &pos);
if(first = null)
{
printf(“\n list is empty”);
}
else if(pos == 1) && (first -> link == null)
{
printf(“\n Deleted element is %d \n”, curr -> data); free(curr);
}
else
{
next = first; while(c < pos)
{
prev = next;
next = next -> link; c++;
}
prev -> link = next -> link; next -> link = null; if(next = null)
{
printf(“\n Invalid position”);
}
else
{
printf(“\n Deleted element is:%d\n”, next -> data); free(next);
if(prev -> link == null)
{
last = prev;
}
}
}
void display()
{
curr = first; while(curr != null)
{
printf(“\n %d”, curr -> data); curr = curr -> link;
}
}
Output:
Singly linked list 1.create
2.insert 3.del 4.exit

Enter your choice 1 Enter the data:2 1.create


2.insert 3.del 4.exit

Enter your choice 2 Enter the data: 4 Enter the position: 2 2


4
1.create 2.insert 3.del 4.exit

Enter your choice 4


LAB : 4

Aim : Represent the given sparse matrix using array and linked list

// C program for Sparse Matrix Representation


// using Linked Lists
#include<stdio.h>
#include<stdlib.h>

// Node to represent sparse matrix


struct Node
{
int value;
int row_position;
int column_postion;
struct Node *next;
};

// Function to create new node


void create_new_node(struct Node** start, int non_zero_element,
int row_index, int column_index )
{
struct Node *temp, *r;
temp = *start;
if (temp == NULL)
{
// Create new node dynamically
temp = (struct Node *) malloc (sizeof(struct Node));
temp->value = non_zero_element;
temp->row_position = row_index;
temp->column_postion = column_index;
temp->next = NULL;
*start = temp;

}
else
{
while (temp->next != NULL)
temp = temp->next;

// Create new node dynamically


r = (struct Node *) malloc (sizeof(struct Node));
r->value = non_zero_element;
r->row_position = row_index;
r->column_postion = column_index;
r->next = NULL;
temp->next = r;

}
}
// 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("%d ", temp->row_position);


temp = temp->next;
}
printf("\n");

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");
}

// Driver of the program


int main()
{
// Assume 4x5 sparse matrix
int sparseMatric[4][5] =
{
{0 , 0 , 3 , 0 , 4 },
{0 , 0 , 5 , 7 , 0 },
{0 , 0 , 0 , 0 , 0 },
{0 , 2 , 6 , 0 , 0 }
};

/* Start with the empty list */


struct Node* start = NULL;

for (int i = 0; i < 4; i++)


for (int j = 0; j < 5; j++)

// Pass only those values which are non - zero


if (sparseMatric[i][j] != 0)
create_new_node(&start, sparseMatric[i][j], i, j);

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:

#include<stdio.h>#define MAX5 int top = -1;


intstack_arr[MAX];
/*Beginofpush*/
voidpush()
{
intpushed_item;
if(top==(MAX-1))
printf("StackOverflow\n");
else
}
}
printf("Entertheitemtobepushedinstack: "); scanf("%d",&pushed_item);
top=top+1;
stack_arr[top]=pushed_item;

/*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 :

#include <stdio.h> #define MAX 50


void insert(); void delete(); void display();
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() */
void insert()
{
int add_item;
if (rear == MAX - 1) printf("Queue Overflow \n");
else
{
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() */
void 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() */
void 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 : 1
Inset the element in queue : 20
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 : 30
Enter your choice : 4
LAB – 8

Aim: Binary search tree implementation :

// C function to search a given key in a given BST


#include <stdio.h>
#include <stdlib.h>
struct node {
int key;
struct node *left, *right;
};
// A utility function to create a new BST node
struct node* newNode(int item)
{
struct node* temp
row_position:0 0 1 1 3 3
column_position:2 4 2 3 1 2
Value:3 4 5 7 2 6

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


temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
// A utility function to insert
// a new node with given key in BST
struct node* insert(struct node* node, int key)
{
// If the tree is empty, return a new node
if (node == NULL)
return newNode(key);
// Otherwise, recur down the tree
if (key < node->key)
node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);
// Return the (unchanged) node pointer
return node;
}
// Utility function to search a key in a BST
struct node* search(struct node* root, int key)
{
// Base Cases: root is null or key is present at root
if (root == NULL || root->key == key)
return root;
// Key is greater than root's key
if (root->key < key)
return search(root->right, key);
// Key is smaller than root's key
return search(root->left, key);
}
// Driver Code
int main()
{
struct node* root = NULL;
root = insert(root, 50);
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
insert(root, 60);
insert(root, 80);

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

Breadth First Search :


#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTICES 50
// This struct represents a directed graph using
// adjacency list representation
typedef struct Graph_t {
// No. of vertices
int V;
bool adj[MAX_VERTICES][MAX_VERTICES];
} Graph;
// Constructor
Graph* Graph_create(int V)
{
Graph* g = malloc(sizeof(Graph));
g->V = V;
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
g->adj[i][j] = false;
}
}
return g;
}
// Destructor
void Graph_destroy(Graph* g) { free(g); }
// Function to add an edge to graph
void Graph_addEdge(Graph* g, int v, int w)
{
// Add w to v’s list.
g->adj[v][w] = true;
}
// Prints BFS traversal from a given source s
void Graph_BFS(Graph* g, int s)
{
// Mark all the vertices as not visited
bool visited[MAX_VERTICES];
for (int i = 0; i < g->V; i++) {
visited[i] = false;
}
// Create a queue for BFS
int queue[MAX_VERTICES];
int front = 0, rear = 0;
// Mark the current node as visited and enqueue it
visited[s] = true;
queue[rear++] = s;
while (front != rear) {
// Dequeue a vertex from queue and print it
s = queue[front++];
printf("%d ", s);
// Get all adjacent vertices of the dequeued
// vertex s.
// If an adjacent has not been visited,
// then mark it visited and enqueue it
for (int adjacent = 0; adjacent < g->V;
adjacent++) {
if (g->adj[s][adjacent] && !visited[adjacent]) {
visited[adjacent] = true;
queue[rear++] = adjacent;
}
}
}
}
// Driver code
int main()
{
// Create a graph
Graph* g = Graph_create(4);
Graph_addEdge(g, 0, 1);
Graph_addEdge(g, 0, 2);
Graph_addEdge(g, 1, 2);
Graph_addEdge(g, 2, 0);
Graph_addEdge(g, 2, 3);
Graph_addEdge(g, 3, 3);
printf("Following is Breadth First Traversal "
"(starting from vertex 2) \n");
Graph_BFS(g, 2);
Graph_destroy(g);
return 0;
}

OUTPUT:
Following is Breadth First Traversal (starting from vertex 2)
2031

You might also like