You are on page 1of 31

DSA WITH C

/*
Name – KUSHAGRA JOSHI
Roll no. - 40
Section - G

QUESTION-1: Write a C Program to store N elements to an array and then send all positive elements of the
array to the end without altering the original sequence.
*/

SOURCE CODE:
#include <stdio.h> int negative
= 0 , positive = 0 ; void func(int
arr[] , int n){ int
left[negative] ; int
right[positive] ; int j = 0 ,
k = 0; for(int i = 0 ; i < n ;i++)
{
if(arr[i] < 0){
left[j++] = arr[i] ;
}else{
right[k++] = arr[i] ;
}
}
j =0; int i = 0 ; while(j < negative){
arr[i++] = left[j++];
}
k=0;
while(k < positive){
arr[i++] = right[k++] ;
}
} int
main(){
int n ;
scanf("%d" , &n) ; int
arr[n] ;
for(int i = 0 ; i < n ;i++){
scanf("%d", &arr[i] ) ;
if(arr[i] >= 0){
positive += 1;
}else{
negative += 1 ;
}
}
func(arr , n) ;
for(int i = 0 ; i < n ; i++){
printf("%d " , arr[i]) ;
}
return 0;
}

1
DSA WITH C

OUTPUT:

Enter the number of elements :


6
Enter the elements :
89 5 -91 62 -20 55 The
resulting array is:
-91 -20 89 5 62 55

2
DSA WITH C

/*
Name – KUSHAGRA JOSHI
Roll no. - 40
Section - G

QUESTION-2: Write a C program to create two linked lists positive and negative from an Original linked
list, so that positive linked list contains all positive elements and negative linked list contains negative
elements. Positive and negative linked lists should use the node of existing original linked list.
*/

SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node{
int data ;
struct Node *next ;
}Node;
Node *insertatend(Node *head, int val){
Node *node = (Node
*)malloc(sizeof(Node)) ; node -> data = val ;
node -> next = NULL ; if(head == NULL){
head = node ;
}
else{
Node *current = head ;
while(current -> next != NULL){
current = current -> next ;
}
current -> next = node ;
}
return head;
}
void display(Node *head){
if(head == NULL){
printf("Empty\n");
return ;
}
Node *current = head ;
while(current != NULL){
printf("%d " , current -> data) ;
current = current -> next;
}
printf("\n") ;
return ;
}
void solve(){
Node *head = NULL ;
int t ;

3
DSA WITH C

printf("Enter -1 to break :\n") ;


while(scanf("%d" ,&t)){
if(t == -1){
break ;
}
head = insertatend(head , t) ;
}
printf("The linked list is : ") ;
display(head) ;
Node *negative =
malloc(sizeof(Node)); negative -> data
= - 1; Node *neg = negative;
Node *positive = malloc(sizeof(Node));
Node *pos = positive ; positive -> data = -
1; Node *current = head ;
while(current != NULL){ if(current -
> data >= 0){ positive -> next =
current ;
positive = current ;
}
else{
negative -> next = current ;
negative = current ;
}
current = current -> next ;
}
positive -> next = NULL ;
negative -> next = NULL ; if(neg ->
next != NULL){
neg = neg -> next ;
}
else{ neg =
NULL ;
}
if(pos -> next != NULL){
pos = pos -> next ;
}
else{
pos= NULL ;
}
printf("Negative : ") ;
display(neg) ;
printf("Positive : ") ;
display(pos) ;
return ;
}
int main(){
solve() ;
}

4
DSA WITH C

OUTPUT:

Enter -1 to break :
35 -18 95 -97 47 89 -4 98 0 -1
The linked list is : 35 -18 95 -97 47 89 -4 98 0
Negative : -18 -97 -4
Positive : 35 95 47 89 98 0

5
DSA WITH C

/*
Name – KUSHAGRA JOSHI
Roll no. - 40
Section - G

QUESTION-3: Write a C program to create a linked list P, then write a ‘C’ function named split to create
two linked lists Q & R from P So that Q contains all elements in odd positions of P and R contains the
remaining elements. Finally print both linked lists i.e Q and R. */

SOURCE CODE:
#include <stdio.h>
#include <stdbool.h> #include
<stdlib.h>
typedef struct Node{
int data ;
struct Node *next ;
}Node;
Node *insertatend(Node *head , int val){
Node *node = (Node *)malloc(sizeof(Node)) ;
node -> data = val ; node -> next = NULL ;
if(head == NULL){
head = node ;
}
else{
Node *current = head ;
while(current -> next != NULL){
current = current -> next ;
}
current -> next = node ;
} return
head ;
}
void display(Node *head)
{ Node *current = head ;
while(current != NULL)
{ printf("%d " , current -
>data) ;
current = current -> next ;
}
printf("\n") ;
return ;
}
void split(Node *P){
if(P == NULL || P -> next == NULL){
display(P) ; return ;
}
Node *q = (Node*)malloc(sizeof(Node)) ;
Node *r = (Node*)malloc(sizeof(Node)) ;
Node *Q = q ;

6
DSA WITH C

Node *R = r ; Node *current


= P ; while(true){ q -> next
= current ; q = q -> next ;
if(current -> next != NULL){
r -> next = current -> next ;
r = r -> next ;
}
else{
break ;
}
if(current -> next -> next == NULL){
break ;
} else{
current = current -> next -> next ;
}
}
q -> next = NULL ;
r -> next = NULL ;
printf("The elements at odd position are : \n") ;
display(Q -> next) ;
printf("The elements at even position are : \n") ;
display(R -> next) ; return ; } void solve()
{ Node *head = NULL ;
int t ;
printf("Enter -1 to break : \n") ;
while(scanf("%d" , &t)){
if(t == -1){ break ;
}
head = insertatend(head , t) ;
}
split(head) ; }
int main()
{ solve() ;}
OUTPUT:
Enter -1 to break :
46 98 -23 98 54 36 -23 -1 The
elements at odd position are :
46 -23 54 -23
The elements at even position are :
98 98 36

7
DSA WITH C

/*
Name – KUSHAGRA JOSHI
Roll no. - 40
Section - G

QUESTION-4: Write a program to add of two polynomials of degree n, using linked list. For example:
p1=an x n +an-1x n-1 + an-2x n-2 + ……..a0 x 0
P2=bn x n +bn-1x n-1 + bn-2x n-2 + ……..b0 x 0 p1
= first polynomial p2 = second polynomial. Find out p3= p1+p2
*/

SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node{
int cons ;
int deg ;
struct Node *next ;
}Node ;
Node *insert(Node *head , int x , int y){
Node *node = (Node *)malloc(sizeof(Node)) ;
node -> cons = x ; node -> deg = y ; node
-> next = NULL ;
if(head == NULL){
head = node ;
}
else{
Node *current = head ;
while(current -> next){
current = current -> next ;
}
current -> next = node ;
} return
head ;
}
void display(Node *head){
if(head == NULL){
return ;
}
Node *current = head ;
while(current -> next){
printf("%dx^%d + " , current -> cons , current -> deg) ;
current = current -> next ;
}
printf("%d \n" , current -> cons) ; return ;
}
Node *add(Node *head1 , Node *head2 , int n , int t){
Node *ptr = head1 ;
Node *current = head2 ;

8
DSA WITH C

Node *res = (Node *)malloc(sizeof(Node)) ;


Node *dn = res;
res -> next = NULL ;
int d = n - t ; if(t >
n){ ptr = head2 ;
current = head1 ;
d=t-n;
} while(d--){
res -> next = ptr ;
res = res -> next ;
ptr = ptr -> next ;
}
while(current != NULL && ptr != NULL)
{ current -> cons = (current -> cons + ptr ->
cons) ;
res -> next = current ;
res = res -> next ; current
= current -> next ; ptr =
ptr -> next ;
}
res -> next = NULL ;
return dn -> next ;
} int
main(){
Node *head= NULL ;
Node *head2 = NULL ;
printf("Enter the highest degree of first polynomial : ") ;
int n ;
scanf("%d" , &n) ;
printf("Enter the coefficients in decreasing order of power : \n") ;
for(int i = n ; i >= 0 ; i--){ int a ; scanf("%d" , &a) ;
head = insert(head , a, i) ;
}
printf("Enter the highest degree of second polynomial : ") ;
int t ;
scanf("%d" , &t) ;
printf("Enter the coefficients in decreasing order of power : \n") ;
for(int i = t ; i >= 0 ; i--){ int x ; scanf("%d" , &x) ;
head2 = insert(head2 , x , i) ;
} printf("First :
") ; display(head) ;
printf("Second : ") ;
display(head2) ;
printf("Result : ") ;
Node *res = add(head , head2 , n , t) ;
display(res) ;
}

OUTPUT:

9
DSA WITH C

Enter the highest degree of first polynomial : 3


Enter the coefficients in decreasing order of power : 9 5 8 4
Enter the highest degree of second polynomial : 2
Enter the coefficients in decreasing order of power : 7 6 3
First : 9x^3 + 5x^2 + 8x^1 + 4
Second : 7x^2 + 6x^1 + 3
Result : 9x^3 + 12x^2 + 14x^1 + 7

/*
Name – KUSHAGRA JOSHI
Roll no. - 40

10
DSA WITH C

Section - G

QUESTION-5: Write a C program to implement time sharing environment (using circular linked list) for N
processes, where CPU allocates time slots of 10ns for given N processes, then print which process will be
completed in how much time.
*/

SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define cputime 10 typedef
struct Node{
int data , idx ;
struct Node *next;
} Node;

Node *insert(Node *head , int i){


Node *node = (Node *)malloc(sizeof(Node));
int val;
printf("Enter time for process %d: \n", i);
scanf("%d", &val); node -> data = val;
node -> idx = i; if (head == NULL){
head = node;
}else{
Node *current = head;
while (current -> next != head){
current = current -> next;
}
current -> next = node;
}
node -> next = head;
return head;
}

void timetaken(Node *head)


{ int total = 0; Node *prev ;
while (true){ if(head -> data
>= cputime){ head ->
data -= cputime; total +=
cputime;
}
else{ total += head -
> data;
head -> data = 0;
}
if (head -> data == 0){
printf("Process %d completed after: %d\n", head -> idx , total) ;
if(head -> next == head){ break ; } else{

11
DSA WITH C

Node *temp = head;


prev -> next = head -> next ;
head = head -> next ;
free(temp) ;
} } else{
prev = head ; head =
head -> next ;
}
}
printf("Total time taken: %d\n",total) ;
}

int main(){
int n ;
printf("Enter No. of Process: ") ;
scanf("%d", &n);
Node *head = NULL;
for (int i = 1; i <= n; i++){
head = insert(head, i);
}
timetaken(head);
}

OUTPUT:

Enter No. of Process: 3 Enter


time for process 1:
30
Enter time for process 2:
50
Enter time for process 3:
60
Process 1 completed after: 70
Process 2 completed after: 120
Process 3 completed after: 140
Total time taken: 140

12
DSA WITH C

/*
Name – KUSHAGRA JOSHI
Roll no. - 40
Section - G

QUESTION-6: Write a C program to create a double linked list by inserting nodes in such a way that the
resultant linked list remains in ascending order. (do not use any sorting technique). */

SOURCE CODE:
#include <stdio.h>
#include <stdbool.h> #include
<stdlib.h>
typedef struct Node{
int data ; struct
Node *next ;
struct Node *prev ;

13
DSA WITH C

}Node;
Node *head = NULL ;
Node *tail = NULL ;
Node *insert(Node *head , int val){
Node *current = head ;
Node *node = (Node *)malloc(sizeof(Node)) ;
node -> data = val ; node -> next = NULL;
node -> prev = NULL; if(head == NULL){
head = tail = node ;
return head ;
}
if(val <= head -> data){
node -> next = head ;
head -> prev = node ;
head = node ; return
head ;
}
if(val >= tail -> data){
tail -> next = node ;
node -> prev = tail ;
tail = node ;
return head ;
} else{
while(true){
if(val <= current -> data){
Node *prev_node = current -> prev ;
prev_node -> next = node ;
node -> next = current ; node
-> prev = prev_node ;
current -> prev = node ;
break ;
} else{
current = current -> next ;
}
} }
return head ; }
void display(Node *head){ Node
*current = head ; while(current !
= NULL){ printf("%d " ,
current -> data) ;
current = current -> next ;
} printf("\
n") ; return ;
}

void solve(){
int t ;
printf("Enter -1 to break") ;

14
DSA WITH C

while(scanf("%d" , &t)){
if(t == -1){ break ;
}
head = insert(head , t) ;
}
printf("The linked list is : \n") ;
display(head) ;
} int
main()
{ solve(
);
}

OUTPUT:

Enter -1 to break
87 -54 2 98 99 43 -1 The
linked list is :
-54 2 43 87 98 99

15
DSA WITH C

/*
Name – KUSHAGRA JOSHI
Roll no. - 40
Section - G

QUESTION-7: Write a C program to create a binary search tree and perform following operations:
1) Search a particular key.
2) Delete a node from the tree.
3) Find total number of leaf nodes
4) Find height of a binary search tree
5) Count total numbers of nodes from right hand side of root node */

SOURCE CODE:
#include <stdio.h> #include
<stdlib.h>
typedef struct Node{
int data ; struct
Node *left ;
struct Node *right ;
}Node ;
void insert(Node **rootnode , int val){
if(*rootnode == NULL){
Node *node = (Node *)malloc(sizeof(Node)) ;
node -> data = val ; node -> left = NULL ;
node -> right = NULL ; *rootnode = node ;
return ;
} else{ if(((*rootnode)) ->
data > val){
insert((&(*rootnode) -> left) ,val) ;

16
DSA WITH C

}
else{ insert((&(*rootnode) -> right) ,
val) ;
}
}
}
void preordertraversal(Node *rootnode){
if(rootnode == NULL){ return ;
}
printf("%d " , rootnode -> data) ;
preordertraversal(rootnode -> left) ; preordertraversal(rootnode -
> right) ; return ;
} void search(Node *rootnode , int
val){
if(rootnode == NULL){ printf("The value is not
found") ; return ;
}
if(rootnode -> data == val){
printf("The value is found") ; return ;
}
if(rootnode -> data > val){
search(rootnode -> left , val) ;
}
else{
search(rootnode -> right , val) ;
}
}
Node *minvalue(Node **rootnode){
Node *current = *rootnode ;
while(current != NULL && current -> left != NULL){
current = current -> left ;
}
return current ;
}
void delete(Node **rootnode , int val){
if(*rootnode == NULL){
return ;
}
if(((*rootnode) -> data) > val){
delete((&(*rootnode) -> left) , val) ;
}
else if(((*rootnode) -> data) < val){
delete((& (*rootnode) -> right) , val) ;
} else{ if((*rootnode) -> left == NULL && (*rootnode) -> right
== NULL){
*rootnode = NULL ; return ;
}
else if((*rootnode) -> left == NULL){
Node *temp = (*rootnode) -> right ;
(*rootnode) -> data = temp -> data;
(*rootnode) -> right = NULL ;
}

17
DSA WITH C

else if((*rootnode) -> right == NULL){


Node *temp = ((*rootnode) -> left) ;
(*rootnode) -> data = temp -> data ;
(*rootnode) -> left = NULL ;
}
else{
Node *nodetobedeleted = minvalue((&(*rootnode) -> right)) ;
(*rootnode) -> data = nodetobedeleted -> data ;
delete((&(*rootnode) -> right) , nodetobedeleted -> data) ;
}
}
}
int totalleafnodes(Node *rootnode){ if(rootnode -> left == NULL
&& rootnode -> right == NULL){ return 1;
}
int a = 0 , b = 0 ;
if(rootnode -> left != NULL){
a = totalleafnodes(rootnode -> left) ;
}
if(rootnode -> right != NULL){
b = totalleafnodes(rootnode -> right) ;
}
return a + b ;
}
int max(int a , int b){
if(a > b){
return a ;
}else{ return b ;
}
}
int height(Node *rootnode){ if(rootnode -> right == NULL &&
rootnode -> left == NULL){
return 0 ;
}
int a = 0 , b =0 ;
if(rootnode -> right != NULL){
a = height(rootnode -> right) ;
}
if(rootnode -> left != NULL){
b = height(rootnode -> left) ;
}
return max(a , b) + 1;
}
int totalrightnodes(Node *rootnode)
{ if(rootnode == NULL){
return 0 ;
}
if(rootnode -> right != NULL){ return 1 +
totalrightnodes(rootnode -> right) ;
}
else{ retur
n0;
}

18
DSA WITH C

}
int main(){
Node *rootnode = NULL ;
int t ;
while(scanf("%d" , &t)){
if(t == -1){
break ;
}
insert(&rootnode , t) ;
}
printf("Preordertraversal : ") ; preordertraversal(rootnode) ; printf("The total number of leaf
nodes are %d: \n" , totalleafnodes(rootnode)) ; printf("The height of the bst is : %d \n" ,
height(rootnode)); printf("The total number of nodes to the right of the rootnode are : %d\n" ,
totalrightnodes(rootnode)); printf("Enter the node to be found : \n") ; int nodetobefound ;
scanf("%d" ,&nodetobefound) ; search(rootnode , nodetobefound) ;
printf("\n") ; printf("Enter the node to
be deleted : ") ; int val ;
scanf("%d" , &val) ;
delete(&rootnode , val) ;
preordertraversal(rootnode) ; return
0;
}

OUTPUT:
Enter -1 to break
67 54 87 12 98 34 76 89 -1
Preordertraversal : 67 54 12 34 87 76 98 89
The total number of leaf nodes are: 3
The height of the bst is : 3
The total number of nodes to the right of the rootnode are : 2 Enter
the node to be found :
98
The value is found
Enter the node to be deleted : 12
67 54 34 87 76 98 89

19
DSA WITH C

/*
Name – KUSHAGRA JOSHI
Roll no. - 40
Section - G

QUESTION-8: Write a C program to sort an unsorted sequence of strings given by user in an array, using
Merge sort technique.
*/

SOURCE CODE:
#include<stdio.h>
#include<stdlib.h>
#include<string.h> #define
mxN 100
void merge(char *arr[] , int l , int mid , int h){
int i = l , j = mid + 1 ;
int k = 0 ;
char **v = malloc(sizeof(char *) * (h - l + 1)) ;
while(i <= mid && j <= h)
{ if(strcmp(arr[i] , arr[j]) < 0){
v[k++] = arr[i++] ;
}
else{
v[k++] = arr[j++] ;
}
}
while(i <= mid)
{ v[k++] = arr[i++] ;
}
while(j <= h)
{ v[k++] = arr[j++]
;
} k
=0;
for(int i = l ; i <= h ; i++)
{ arr[i] = v[k++] ;
}
return ;
}
void mergesort(char *arr[] , int l , int h){
if(l >= h){ return ;
}
int mid = (l + h) / 2 ;
mergesort(arr , l , mid) ;
mergesort(arr , mid + 1 , h) ;
merge(arr , l , mid , h) ;
} int
main(){

20
DSA WITH C

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


int n ; scanf("%d " , &n) ; char**
arr = malloc(sizeof(char *)* n);
printf("Enter the strings : \n") ;
for(int i = 0 ; i < n ; i++){

arr[i] = malloc(sizeof(char) * mxN);


scanf("%s",arr[i]);
}
mergesort(arr , 0 , n - 1) ;
printf("The strings in increasing order are : \n") ;
for(int i = 0 ; i < n ; i++)
{ printf("%s " , arr[i]) ;
}
return 0;

OUTPUT:

21
DSA WITH C

Enter the number of strings : 6

Enter the strings :


Nobody is coming to save you

The strings in increasing order are :


Nobody coming is save to you

22
DSA WITH C

/*
Name – KUSHAGRA JOSHI
Roll no. - 40
Section - G

QUESTION-9: Write a C program to implement linked representation of a graph in memory using array of
pointers.
*/

SOURCE CODE:
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h> int
visited[1000] = {0} ;
typedef struct Node{ int
data ; struct Node
*next ;
}Node ; typedef
struct adjlist{
Node *head ;
}adjlist ; typedef
struct Graph{
int v ;
struct adjlist *arr ;
}Graph ;
Graph *create(int v){
Graph *gr = (Graph *)malloc(sizeof(Graph)) ;
gr -> v = v ;
gr -> arr = (adjlist *)malloc((v + 1) * sizeof(adjlist)) ;
for(int i = 1 ; i <= v ; i++){
gr -> arr[i].head = NULL ;
}
return gr ;
}
Node *newNode(int val){
Node *node = (Node
*)malloc(sizeof(Node)) ; node -> data = val ;
node -> next = NULL ; return node ;
} void addedge(Graph *gr , int u , int
v){
Node *node = newNode(v) ;
if(gr -> arr[u].head == NULL){
gr -> arr[u].head = node ;
}
else{
node -> next = gr -> arr[u].head ;
gr -> arr[u].head = node ;
}

23
DSA WITH C

Node *newnode = newNode(u) ;


if(gr -> arr[v].head == NULL){
gr -> arr[v].head = newnode ;
}
else{
newnode -> next = gr -> arr[v].head ;
gr -> arr[v].head = newnode ;
}
}
void display(Graph *gr){ for(int i = 1 ; i <= gr ->
v ; i++){ printf("%d ---->" , i) ;
Node *current = gr -> arr[i].head ;
while(current != NULL){
printf("%d " , current -> data) ;
current = current -> next ;
}
printf("\n") ;
}
return ;
} void
solve(){
int n , m ;
printf("Enter the number of vertices and the number of edges\n") ;
scanf("%d %d" , &n , &m) ; Graph *gr = create(n) ;
printf("Enter the source and destination of each edge : ") ;
for(int i = 0; i < m ; i++){
int x , y ;
scanf("%d %d", &x , &y) ;
addedge(gr , x , y) ;
}
printf("The linked list representation of graph is : \n") ;
display(gr) ; return ;
}
int main(){
solve() ;
}

OUTPUT:

Enter the number of vertices and the number of edges


55
Enter the source and destination of each edge :
12
23
13
24
34
The linked list representation of graph is :
1 ---->3 2

24
DSA WITH C

2 ---->4 3 1
3 ---->4 1 2
4 ---->3 2
5 ---->

25
DSA WITH C

/*
Name – KUSHAGRA JOSHI
Roll no. - 40
Section - G

QUESTION-10: Write a C program to implement DFS.


*/

SOURCE CODE:
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h> int
visited[1000] = {0} ;
typedef struct Node{ int
data ; struct Node
*next ;
}Node ; typedef
struct adjlist{
Node *head ;
}adjlist ; typedef
struct Graph{
int v ;
struct adjlist
*arr ; }Graph ;
Graph *create(int v){
Graph *gr = (Graph *)malloc(sizeof(Graph)) ;
gr -> v = v + 1 ;
gr -> arr = (adjlist *)malloc((v + 1) * sizeof(adjlist)) ;
for(int i = 1 ; i <= v ; i++){
gr -> arr[i].head = NULL ;
}
return gr ;
}
Node *newNode(int val){
Node *node = (Node
*)malloc(sizeof(Node)) ; node -> data = val ;
node -> next = NULL ;
return node ;
} void addedge(Graph *gr , int u , int
v){
Node *node = newNode(v) ;
if(gr -> arr[u].head == NULL){
gr -> arr[u].head = node ;
}
else{
node -> next = gr -> arr[u].head ;
gr -> arr[u].head = node ;
}

26
DSA WITH C

Node *newnode = newNode(u) ;


if(gr -> arr[v].head == NULL){
gr -> arr[v].head = newnode ; }
else{
newnode -> next = gr -> arr[v].head ;
gr -> arr[v].head = newnode ;
}
}

void dfs(Graph *gr , int current){


printf("%d " , current) ;
visited[current] = 1 ;
Node *newcurrent = gr -> arr[current].head ;
while(newcurrent != NULL){ if(!
visited[newcurrent -> data]){
dfs(gr, newcurrent -> data) ;
}
newcurrent = newcurrent -> next ;
}
} void
solve(){
int n , m ;
printf("Enter the number of vertices and the number of edges\n") ;
scanf("%d %d" , &n , &m) ;
Graph *gr = create(n) ;
printf("Enter the source and destination of each edge : \n") ;
for(int i = 0; i < m ; i++){
int x , y ;
scanf("%d %d", &x , &y) ;
addedge(gr , x , y) ;
}
printf("DFS Traversal : ") ;
for(int i = 1 ; i <= n; i++){
if(!visited[i]){
dfs(gr , i) ;
}
}
return ;
}
int main(){
solve() ;
}

OUTPUT:
Enter the number of vertices and the number of edges
44
Enter the source and destination of each edge :
13
12

27
DSA WITH C

23
24
DFS Traversal : 1 2 4 3

28
DSA WITH C

/*
Name – KUSHAGRA JOSHI
Roll no. - 40
Section - G

QUESTION-11: Write a C program to implement Kruskal’s algorithm.


*/

SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct Edge{
int w , x ,
y ; } Edge ; typedef
struct Graph{ int V , E
; Edge
*edgelist ;
}Graph ;
Graph *create(int n , int m){
Graph *gr = (Graph *)malloc(sizeof(Graph)) ;
gr -> V = n ;
gr -> E = m ;
gr -> edgelist = (Edge *)malloc(sizeof(Edge) * (m + 1)) ;
return gr ;
} int *parent ;
int *rank ;
void init(int n){
parent = (int *)malloc(sizeof(int) * (n + 1)) ;
rank = (int *)malloc(sizeof(int) * (n + 1)) ; for(int i =
1 ; i <= n ; i++){
parent[i] = -1 ;
rank[i] = 1 ;
}
return ;
} int findset(int
x){
if(parent[x] == -1){
return x ;
}
return parent[x] = findset(parent[x]) ;
} void unite(int x , int
y){ int s1 =
findset(x) ; int s2 =
findset(y) ;

if(s1 != s2)
{ if(rank[s1] < rank[s2])
{ parent[s1] = s2 ;

29
DSA WITH C

rank[s2] += rank[s1] ; }
else{ parent[s2] = s1 ;
rank[s1] += rank[s2] ;
}
}
return ; }
int comp(const void *a , const void *b){
Edge *x = (Edge *)a ;
Edge *y = (Edge *)b ;
return x -> w > y -> w ;
} int kruskal(Graph *gr){ int answer = 0 ;
for(int i = 0 ; i < gr -> E ; i++){ int s1
= findset(gr -> edgelist[i].x) ;
int s2 = findset(gr -> edgelist[i].y) ;
if(s1 != s2){
unite(s1 , s2) ;
answer += gr -> edgelist[i].w ;
}
}
return answer ;
} void
solve(){
int n , m ;
printf("Enter the number of vertices and edges\n") ;
scanf("%d %d" , &n , &m) ;
Graph *gr = create(n , m) ; init(n) ;
printf("Enter the source , destination and the weight of the edge \n") ;
for(int i = 0 ; i < m ; i++){ int x , y , w ;
scanf("%d %d %d" , &x , &y ,
&w) ; gr -> edgelist[i].x = x ;
gr -> edgelist[i].y = y ;
gr -> edgelist[i].w = w ;
}
qsort(gr -> edgelist , gr -> E , sizeof(gr -> edgelist[0]) , comp) ;
printf("The cost of minimum spanning tree is : %d \n" , kruskal(gr)) ;
} int
main(){
solve() ;
}

OUTPUT:

Enter the number of vertices and edges


45
Enter the source, destination and the weight of the edge
1 2 10
2 3 15
135

30
DSA WITH C

422
4 3 40
The cost of minimum spanning tree is : 17

31

You might also like