Task Soln l12
Task Soln l12
PROBLEM 1:
Given an array of integers nums and an integer target, return indices of the two numbers such
that they add up to target.
You may assume that each input would have exactly one solution, and you may not use
the same element twice.
You can return the answer in any order.
#include <stdio.h>
int main()
{
int A[] = { 1,2,3,4,5,6,7,8};
int n = 3;
int arr_size = sizeof(A) / sizeof(A[0]);
int i,j,k=0;
int sum[100];
for (i = 0; i < arr_size; i++)
{
for(j=i+1;j<arr_size;j++)
{
sum[k]=A[i]+A[j];
if(sum[k]==n)
{
printf("\n%d\t%d",i,j);
}
k++;
}
}
return 0;
}
PROBLEM 2
Given a sorted array arr[] of N integers, The task is to find the multiple missing elements in
the array between the ranges [arr[0], arr[N-1]].
#include <stdio.h>
#include <stdlib.h>
// Driver code
int main()
{
int arr[] = {1,2,4,6};
PROBLEM 3:
Given an array of distinct integers arr,find all pairs of elements with the minimum absolute
difference of any two elements.
Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows
a, b are from arr
a<b
b - a equals to the minimum absolute difference of any two elements in arr.
#include<stdio.h>
#include<limits.h>
#include<math.h>
main()
{
printf("Enter the size of the array:");
int size;
scanf("%d",&size);
int arr[size];
int i,j,p;
printf("Enter the Element of the array:\n");
for(i=0;i<size;i++)
{
scanf("%d",&arr[i]);
}
int Min_diff=INT_MAX;
for(i=0;i<size-1;i++)
{
for(j=i+1;j<size;j++)
{
if(abs(arr[j]-arr[i])<Min_diff)
{
Min_diff=abs(arr[j]-arr[i]);
}
}}
printf("Minimum difference between two Element is %d",Min_diff);
}
PROBLEM 4:
Implement a program to left rotate the elements of an array with given k rotations.
#include <stdio.h>
int main()
{
//Initialize array
int arr[] = {1, 2, 3, 4, 5};
//Calculate length of array arr
int length = sizeof(arr)/sizeof(arr[0]);
//n determine the number of times an array should be rotated
int n = 3;
printf("\n");
#include<stdlib.h>
struct node{
int data;
};
// Base case
if (head == NULL)
return NULL;
struct node* temp;
curr = head;
temp = curr->link;
curr->link = prev;
prev = curr;
curr = temp;
if (curr != head) {
head->link = curr;
return prev;
return head;
int main(){
int n,Data;
scanf("%d",&n);
scanf("%d",&Data);
head->data = Data;
head->link = NULL;
tmp = head;
scanf("%d",&Data);
current->data = Data;
current->link = NULL;
tmp->link = current;
tmp = tmp->link;
head = reverse(head,NULL);
// Traversing
printf("....Display..... \n");
ptr = head;
while(ptr != NULL){
printf("Value: %d\n",ptr->data);
ptr = ptr->link;
return 0;
if(head==NULL)
{
ptr->next = NULL;
ptr->prev=NULL;
ptr->data=item;
head=ptr;
}
else
{
ptr->data=item;
ptr->prev=NULL;
ptr->next = head;
head->prev=ptr;
head=ptr;
}
printf("\nNode inserted\n");
}
}
void insertion_last()
{
struct node *ptr,*temp;
int item;
ptr = (struct node *) malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
{
printf("\nEnter value");
scanf("%d",&item);
ptr->data=item;
if(head == NULL)
{
ptr->next = NULL;
ptr->prev = NULL;
head = ptr;
}
else
{
temp = head;
while(temp->next!=NULL)
{
temp = temp->next;
}
temp->next = ptr;
ptr ->prev=temp;
ptr->next = NULL;
}
}
printf("\nnode inserted\n");
}
void insertion_specified()
{
struct node *ptr,*temp;
int item,loc,i;
ptr = (struct node *)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("\n OVERFLOW");
}
else
{
temp=head;
printf("Enter the location");
scanf("%d",&loc);
for(i=0;i<loc;i++)
{
temp = temp->next;
if(temp == NULL)
{
printf("\n There are less than %d elements", loc);
return;
}
}
printf("Enter value");
scanf("%d",&item);
ptr->data = item;
ptr->next = temp->next;
ptr -> prev = temp;
temp->next = ptr;
temp->next->prev=ptr;
printf("\nnode inserted\n");
}
}
void deletion_beginning()
{
struct node *ptr;
if(head == NULL)
{
printf("\n UNDERFLOW");
}
else if(head->next == NULL)
{
head = NULL;
free(head);
printf("\nnode deleted\n");
}
else
{
ptr = head;
head = head -> next;
head -> prev = NULL;
free(ptr);
printf("\nnode deleted\n");
}
}
void deletion_last()
{
struct node *ptr;
if(head == NULL)
{
printf("\n UNDERFLOW");
}
else if(head->next == NULL)
{
head = NULL;
free(head);
printf("\nnode deleted\n");
}
else
{
ptr = head;
if(ptr->next != NULL)
{
ptr = ptr -> next;
}
ptr -> prev -> next = NULL;
free(ptr);
printf("\nnode deleted\n");
}
}
void deletion_specified()
{
struct node *ptr, *temp;
int val;
printf("\n Enter the data after which the node is to be deleted : ");
scanf("%d", &val);
ptr = head;
while(ptr -> data != val)
ptr = ptr -> next;
if(ptr -> next == NULL)
{
printf("\nCan't delete\n");
}
else if(ptr -> next -> next == NULL)
{
ptr ->next = NULL;
}
else
{
temp = ptr -> next;
ptr -> next = temp -> next;
temp -> next -> prev = ptr;
free(temp);
printf("\nnode deleted\n");
}
}
void display()
{
struct node *ptr;
printf("\n printing values...\n");
ptr = head;
while(ptr != NULL)
{
printf("%d\n",ptr->data);
ptr=ptr->next;
}
}
void search()
{
struct node *ptr;
int item,i=0,flag;
ptr = head;
if(ptr == NULL)
{
printf("\nEmpty List\n");
}
else
{
printf("\nEnter item which you want to search?\n");
scanf("%d",&item);
while (ptr!=NULL)
{
if(ptr->data == item)
{
printf("\nitem found at location %d ",i+1);
flag=0;
break;
}
else
{
flag=1;
}
i++;
ptr = ptr -> next;
}
if(flag==1)
{
printf("\nItem not found\n");
}
}
PROBLEM 3:
Given a singly linked list, find if the linked list is circular or not.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
struct Node
{
int data;
struct Node* next;
};
/* Should return true if linked list is circular, else false */
bool isCircular(struct Node *head){
//code here
if(head==NULL) return true;
struct Node *t;
t=head;
while(t->next!=NULL && t->next!=head){
t=t->next;
}
return (t->next==NULL)?false:true;
}
int main()
{
int t;
scanf("%d", &t);
while (t--)
{
int n, k;
scanf("%d", &n);
scanf("%d", &k);
int first;
scanf("%d", &first);
struct Node *head;
head = (struct Node *) malloc(sizeof(struct Node));
head->data = first;
head->next = NULL;
struct Node *tail = head;
int i;
for ( i = 1; i < n; ++i)
{
int data;
scanf("%d", &data);
struct Node *temp;
temp = (struct Node *) malloc(sizeof(struct Node));
temp->data = data;
temp->next = NULL;
tail->next = temp;
tail = tail->next;
}
#include<stdio.h>
int stack[100],choice,n,top,x,i;
void push(void);
void pop(void);
void display(void);
int main()
{
//clrscr();
top=-1;
int k;
printf("\n Enter the size of STACK[MAX=100]:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
push();
}
printf("\nNo.of.operations:");
//printf("\n\t--------------------------------");
scanf("%d",&k);
for(i=0;i<k;i++)
{
{
pop();
}
}
if(top>=0)
{
int max=stack[top]+1;
printf("\n%d",max);
}
else
{
printf("n-1");
}
return 0;
}
void push()
{
if(top>=n-1)
{
printf("\n\tSTACK is over flow");
}
else
{
printf(" \n Enter a value to be pushed:");
scanf("%d",&x);
top++;
stack[top]=x;
}
}
void pop()
{
if(top<=-1)
{
printf("\n\t -1");
}
else
{
//printf("\n\t The popped elements is %d",stack[top]);
top--;
}
}
PROBLEM 2:
Find all elements in an array that are greater than all elements to their right.
#include<stdio.h>>
int stack[100],choice,n,top,x,i;
int a[10];
void push();
void pop(void);
int main()
{
top=-1;
printf("\n Enter the size of array:");
scanf("%d",&n);
printf("\nenter the elements:\n");
for (i=0;i<n;i++)
{
scanf("\n %d",&a[i]);
}
printf("\n Greater elements");
for (i=0;i<n;i++)
{
if(stack[top]==-1 || a[i]>stack[top])
{
push(a[i]);
//printf("\n pushed: %d",a[i]);
}
else if(stack[top]>a[i])
{
pop();
push(a[i]);
//printf("\n pushed: %d",a[i]);
}
}
printf("\n%d",stack[top]);
return 0;
}
void push(int x)
{
if(top>=n-1)
{
printf("\n\tSTACK is over flow");
}
else
{
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]);
printf("\n%d",stack[top]);
top--;
}
}
PROBLEM 3:
Transform the given infix expression to postfix form
#include<stdio.h>
#include<ctype.h>
char stack[100];
int top = -1;
void push(char x)
{
stack[++top] = x;
}
char pop()
{
if(top == -1)
return -1;
else
return stack[top--];
}
int priority(char x)
{
if(x == '(')
return 0;
if(x == '+' || x == '-')
return 1;
if(x == '*' || x == '/')
return 2;
return 0;
}
int main()
{
char exp[100];
char *e, x;
printf("Enter the expression : ");
scanf("%s",exp);
printf("\n");
e = exp;
while(*e != '\0')
{
if(isalnum(*e))
printf("%c ",*e);
else if(*e == '(')
push(*e);
else if(*e == ')')
{
while((x = pop()) != '(')
printf("%c ", x);
}
else
{
while(priority(stack[top]) >= priority(*e))
printf("%c ",pop());
push(*e);
}
e++;
}
while(top != -1)
{
printf("%c ",pop());
}return 0;
}
PROBLEM 4:
Program to check for balanced parenthesis Using a stack to balance parenthesis will help you
balance different types of grouping operators such as[],{}and()and verify that they are
correctly nested.
#include <stdio.h>>
#include <conio.h>>
char st[20];
int top=-1;
void psh(char);
char pop();
int main()
{
char a[20],t;
int i,f=1;
scanf("%s",&a);
for(i=0;i<strlen(a);i++)
{
if(a[i]=='('||a[i]=='{'||a[i]=='[')
psh(a[i]);
if(a[i]==')'||a[i]=='}'||a[i]==']')
{
if(top==-1)
f=0;
else
{t=pop();
if(a[i]==')'&&(t=='['||t=='{'))
f=0;
if(a[i]=='}'&&(t=='('||t=='['))
f=0;
if(a[i]==']'&&(t=='{'||t=='('))
f=0;
}
}
}
if(top>=0)
f=0;
if(f==0)
printf("Unbalanced\n");
else
printf("Balanced\n");
return 0;
}
void psh(char a)
{
st[++top]=a;
}
char pop()
{
return st[top--];
}
PROBLEM 5:
Suppose the number of discs in the Tower of Hanoi is N. You need to find the number of
moves required to move the discs from the start peg to the destination peg in the tower.
#include <stdio.h>
int main()
{
int num;
}
void delete()
{
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;
}
printf("\nvalue deleted ");
}
}
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]);
}
}
}
PROBLEM 2:
A queue is an abstract data type that maintains the order in which elements were added to it,
allowing the oldest elements to be removed from the front and new elements to be added to
the rear. This is called a First-In-First-Out (FIFO) data structure because the first element
added to the queue (i.e., the one that has been waiting the longest) is always the first one to be
removed.
A basic queue has the following operations:
Enqueue: add a new element to the end of the queue.
Dequeue: remove the element from the front of the queue and return it.
In this challenge, you must first implement a queue using two stacks.
#include <stdio.h>
#include <stdlib.h>
void push1(int);
void push2(int);
int pop1();
int pop2();
void enqueue();
void dequeue();
void display();
void create();
int stack1[100], stack2[100];
int top1 = -1, top2 = -1;
int count = 0;
/* Main Function */
int main()
{
int choice;
printf("\nQUEUE USING STACKS IMPLEMENTATION\n\n");
printf("\n1.ENQUEUE");
printf("\n2.DEQUEUE");
printf("\n3.DISPLAY");
printf("\n4.EXIT");
printf("\n");
create();
while (1)
{
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);
default:
printf("\nInvalid Choice\n");
}}}
PROBLEM 3:
Ravi sharma wants to store a FIFO data with a maximum size.so he planned for the
circular queue in which we can enter the value in empty spaces.he wants to insert a set of
alphabets in the circular queue.helps him to implement the circular queue
// Circular Queue implementation in C
#include <stdio.h>
#define SIZE 5
char items[SIZE];
int front = -1, rear = -1;
// Adding an element
void enQueue(char 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 -> %c", element);
}
}
// Removing an element
char deQueue() {
char element;
if (isEmpty()) {
printf("\n Queue is empty !! \n");
return (-1);
} else {
element = items[front];
if (front == rear) {
front = -1;
rear = -1;
}
// Q has only one element, so we reset the
// queue after dequeing it. ?
else {
front = (front + 1) % SIZE;
}
printf("\n Deleted element -> %c \n", element);
return (element);
}
}
int main() {
// Fails because front = -1
deQueue();
enQueue('a');
enQueue('b');
enQueue('c');
enQueue('d');
enQueue('e');
display();
deQueue();
display();
enQueue('g');
display();
return 0;
}
##################################################################################
#include <stdio.h>
#include <stdlib.h>
struct node {
int key;
struct node *left, *right;
};
// Create a node
struct node *newNode(int item) {
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
// Inorder Traversal
void inorder(struct node *root) {
if (root != NULL) {
// Traverse left
inorder(root->left);
// Traverse root
printf("%d -> ", root->key);
// Traverse right
inorder(root->right);
}
}
// Insert a node
struct node *insert(struct node *node, int key) {
// Return a new node if the tree is empty
if (node == NULL) return newNode(key);
return node;
}
return current;
}
// Deleting a node
struct node *deleteNode(struct node *root, int key) {
// Return if the tree is empty
if (root == NULL) return root;
else {
// If the node is with only one child or no child
if (root->left == NULL) {
struct node *temp = root->right;
free(root);
return temp;
} else if (root->right == NULL) {
struct node *temp = root->left;
free(root);
return temp;
}
// Driver code
int main() {
struct node *root = NULL;
root = insert(root, 8);
root = insert(root, 3);
root = insert(root, 1);
root = insert(root, 6);
root = insert(root, 7);
root = insert(root, 10);
root = insert(root, 14);
root = insert(root, 4);
Task 5.B:
i)using recursion
// Tree traversal in C
#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);
}
return newNode;
}
int main() {
struct node* root = createNode(1);
insertLeft(root, 12);
insertRight(root, 9);
insertLeft(root->left, 5);
insertRight(root->left, 6);
while (!done)
{
/* Reach the left most tNode of the current tNode */
if(current != NULL)
{
/* place pointer to a tree node on the stack before traversing
the node's left subtree */
push(&s, current);
current = current->left;
}
/* backtrack from the empty subtree and visit the tNode
at the top of the stack; however, if the stack is empty,
you are done */
else
{
if (!isEmpty(s))
{
current = pop(&s);
printf("%d ", current->data);
/* UTILITY FUNCTIONS */
/* Function to push an item to sNode*/
void push(struct sNode** top_ref, struct tNode *t)
{
/* allocate tNode */
struct sNode* new_tNode =
(struct sNode*) malloc(sizeof(struct sNode));
if(new_tNode == NULL)
{
printf("Stack Overflow \n");
getchar();
exit(0);
}
return(tNode);
}
inOrder(root);
getchar();
return 0;
}
Task 5.D:
#include <stdio.h>
#include <stdlib.h>
return newNode;
}
int main()
{
//Add nodes to the binary tree
root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->right->left = createNode(5);
root->right->right = createNode(6);
root->right->right->right= createNode(7);
root->right->right->right->right = createNode(8);
Task 5.E:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int info;
struct node *left, *right;
};
struct node *createnode(int key)
{
struct node *newnode = (struct node*)malloc(sizeof(struct node));
newnode->info = key;
newnode->left = NULL;
newnode->right = NULL;
return(newnode);
}
void inorder(struct node *root)
{
if(root != NULL)
{
inorder(root->left);
printf(" %d ",root->info);
inorder(root->right);
}
}
void smallest(struct node *root)
{
while(root != NULL && root->left != NULL)
{
root = root->left;
}
printf("\nSmallest value is %d\n", root->info);
}
void largest(struct node *root)
{
while (root != NULL && root->right != NULL)
{
root = root->right;
}
printf("\nLargest value is %d", root->info);
}
/*
* Main Function
*/
int main()
{
/* Creating first Tree. */
struct node *newnode = createnode(25);
newnode->left = createnode(17);
newnode->right = createnode(35);
newnode->left->left = createnode(13);
newnode->left->right = createnode(19);
newnode->right->left = createnode(27);
newnode->right->right = createnode(55);
/* Sample Tree 1:
* 25
* / \
* 17 35
* /\ /\
* 13 19 27 55
*/
printf("Inorder traversal of tree 1 :");
inorder(newnode);
largest(newnode);
smallest(newnode);
TASK-6-HASHING
PROBLEM 1: LINEAR PROBING
#include <stdio.h>
#include<stdlib.h>
#define TABLE_SIZE 10
int h[TABLE_SIZE]={NULL};
void insert()
{
int key,index,i,flag=0,hkey;
printf("\nenter a value to insert into hash table\n");
scanf("%d",&key);
hkey=key%TABLE_SIZE;
for(i=0;i<TABLE_SIZE;i++)
{
index=(hkey+i)%TABLE_SIZE;
if(h[index] == NULL)
{
h[index]=key;
break;
}
if(i == TABLE_SIZE)
void display()
{
int i;
printf("\nelements in the hash table are \n");
}
main()
{
int opt,i;
while(1)
{
printf("\nPress 1. Insert\t 2. Display \t3. Search \t4.Exit \n");
scanf("%d",&opt);
switch(opt)
{
case 1:
insert();
break;
case 2:
display();
break;
case 3:
exit(0);
}
}
}
#include <stdio.h>
#include <stdlib.h>
#define TABLE_SIZE 10
struct node
{
int data;
struct node *next;
};
struct node *head[TABLE_SIZE]={NULL},*c;
void insert()
{
int i,key;
printf("\nenter a value to insert into hash table\n");
scanf("%d",&key);
i=key%TABLE_SIZE;
struct node * newnode=(struct node *)malloc(sizeof(struct node));
newnode->data=key;
newnode->next = NULL;
if(head[i] == NULL)
head[i] = newnode;
else
{
c=head[i];
while(c->next != NULL)
{
c=c->next;
}
c->next=newnode;
}
}
void display()
{
int i;
for(i=0;i<TABLE_SIZE;i++)
{
printf("\nentries at index %d\n",i);
if(head[i] == NULL)
{
printf("No Hash Entry");
}
else
{
for(c=head[i];c!=NULL;c=c->next)
printf("%d->",c->data);
}
}
}
main()
{
int opt,key,i;
while(1)
{
printf("\nPress 1. Insert\t 2. Display \t 3.Exit \n");
scanf("%d",&opt);
switch(opt)
{
case 1:
insert();
break;
case 2:
display();
break;
case 3:
exit(0);
}
}
}
PROBLRM 3:
#include<stdio.h>
#include <string.h>
int main()
{
char s[1000];
int i,j,k,count=0,n;
for(j=0;s[j];j++);
n=j;
for(i=0;i<n;i++)
{
count=1;
if(s[i])
{
for(j=i+1;j<n;j++)
{
if(s[i]==s[j])
{
count++;
s[j]='\0';
}
}
printf(" '%c' = %d \n",s[i],count);
return 0;
}
PROBLEM 4:
Given an array which may contain duplicates, print all elements and their frequencies
using hashing
#include <stdio.h>
int main()
{
//Initialize array
int i,j;
int arr[] = {10, 20, 20, 10, 10, 20, 5, 20};
//Calculate length of array arr
int length = sizeof(arr)/sizeof(arr[0]);
TASK-7 GRAPH
PROBLEM 1:
#include <stdio.h>
// N vertices and M Edges
int N, M;
// Function to create Adjacency Matrix
void createAdjMatrix(int Adj[][N + 1],
int arr[][2])
{
// Initialise all value to this
// Adjacency list to zero
int i,j;
for (i = 0; i < N + 1; i++) {
// Update value to 1
Adj[x][y] = 1;
Adj[y][x] = 1;
}
}
// Driver Code
int main()
{
// Number of vertices
N = 5;
// Given Edges
int arr[][2]
= { { 1, 2 }, { 2, 3 },
{ 4, 5 }, { 1, 5 } };
// Number of Edges
M = sizeof(arr) / sizeof(arr[0]);
// For Adjacency Matrix
int Adj[N + 1][N + 1];
return 0;
}
OUTPUT
01001
10100
01000
00001
10010
PROBLEM 2:
#include <limits.h>
#include <stdio.h>
#include <stdbool.h>
return min_index;
}
int graph[V][V] = { { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
{ 4, 0, 8, 0, 0, 0, 0, 11, 0 },
{ 0, 8, 0, 7, 0, 4, 0, 0, 2 },
{ 0, 0, 7, 0, 9, 14, 0, 0, 0 },
{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },
{ 0, 0, 4, 14, 10, 0, 2, 0, 0 },
{ 0, 0, 0, 0, 0, 2, 0, 1, 6 },
{ 8, 11, 0, 0, 0, 0, 1, 0, 7 },
{ 0, 0, 2, 0, 0, 0, 6, 7, 0 } };
dijkstra(graph, 0);
return 0;
}
Output:
PROBLEM 3:
// Prim's Algorithm in C
#include<stdio.h>
#include<stdbool.h>
int main() {
int no_edge; // number of edge
return 0;
}
OUTPUT:
Edge : Weight
0-1:9
1 - 3 : 19
3 - 4 : 31
3 - 2 : 51
PROBLEM 4:
// Kruskal's algorithm in C
#include <stdio.h>
#define MAX 30
edge_list elist;
int Graph[MAX][MAX], n;
edge_list spanlist;
void kruskalAlgo();
int find(int belongs[], int vertexno);
void applyUnion(int belongs[], int c1, int c2);
void sort();
void print();
sort();
spanlist.n = 0;
if (cno1 != cno2) {
spanlist.data[spanlist.n] = elist.data[i];
spanlist.n = spanlist.n + 1;
applyUnion(belongs, cno1, cno2);
}
}
}
// Sorting algo
void sort() {
int i, j;
edge temp;
int main() {
int i, j, total_cost;
n = 6;
Graph[0][0] = 0;
Graph[0][1] = 4;
Graph[0][2] = 4;
Graph[0][3] = 0;
Graph[0][4] = 0;
Graph[0][5] = 0;
Graph[0][6] = 0;
Graph[1][0] = 4;
Graph[1][1] = 0;
Graph[1][2] = 2;
Graph[1][3] = 0;
Graph[1][4] = 0;
Graph[1][5] = 0;
Graph[1][6] = 0;
Graph[2][0] = 4;
Graph[2][1] = 2;
Graph[2][2] = 0;
Graph[2][3] = 3;
Graph[2][4] = 4;
Graph[2][5] = 0;
Graph[2][6] = 0;
Graph[3][0] = 0;
Graph[3][1] = 0;
Graph[3][2] = 3;
Graph[3][3] = 0;
Graph[3][4] = 3;
Graph[3][5] = 0;
Graph[3][6] = 0;
Graph[4][0] = 0;
Graph[4][1] = 0;
Graph[4][2] = 4;
Graph[4][3] = 3;
Graph[4][4] = 0;
Graph[4][5] = 0;
Graph[4][6] = 0;
Graph[5][0] = 0;
Graph[5][1] = 0;
Graph[5][2] = 2;
Graph[5][3] = 0;
Graph[5][4] = 3;
Graph[5][5] = 0;
Graph[5][6] = 0;
kruskalAlgo();
print();
}
OUTPUT:
2-1:2
5-2:2
3-2:3
4-3:3
1-0:4
PROBLEM 5:
#include<stdio.h>
#include<conio.h>
int main(){
int i,j,k,n,a[10][10],indeg[10],flag[10],count=0;
printf("Enter the no of vertices:\n");
scanf("%d",&n);
printf("Enter the adjacency matrix:\n");
for(i=0;i<n;i++){
printf("Enter row %d\n",i+1);
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
}
for(i=0;i<n;i++){
indeg[i]=0;
flag[i]=0; }
for(i=0;i<n;i++)
for(j=0;j<n;j++)
indeg[i]=indeg[i]+a[j][i];
printf("\nThe topological order is:");
while(count<n){
for(k=0;k<n;k++){
if((indeg[k]==0) && (flag[k]==0)){
printf("%d ",(k+1));
flag [k]=1;
}
for(i=0;i<n;i++){
if(a[i][k]==1)
indeg[k]--;
} }
count++;
} return 0;}
OUTPUT
PROBLEM 6:
#include <stdio.h>
#include <stdlib.h>
struct node {
int vertex;
struct node* next;
};
struct node* createNode(int v);
struct Graph {
int numVertices;
int* visited;
// DFS algo
void DFS(struct Graph* graph, int vertex) {
struct node* adjList = graph->adjLists[vertex];
struct node* temp = adjList;
graph->visited[vertex] = 1;
printf("Visited %d \n", vertex);
if (graph->visited[connectedVertex] == 0) {
DFS(graph, connectedVertex);
}
temp = temp->next;
}
}
// Create a node
struct node* createNode(int v) {
struct node* newNode = malloc(sizeof(struct node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}
// Create graph
struct Graph* createGraph(int vertices) {
struct Graph* graph = malloc(sizeof(struct Graph));
graph->numVertices = vertices;
int i;
for (i = 0; i < vertices; i++) {
graph->adjLists[i] = NULL;
graph->visited[i] = 0;
}
return graph;
}
// Add edge
void addEdge(struct Graph* graph, int src, int dest) {
// Add edge from src to dest
struct node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;
int main() {
struct Graph* graph = createGraph(4);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 2);
addEdge(graph, 2, 3);
printGraph(graph);
DFS(graph, 2);
return 0;
}
OUTPUT:
PROBLEM 7:
// BFS algorithm in C
#include <stdio.h>
#include <stdlib.h>
#define SIZE 40
struct queue {
int items[SIZE];
int front;
int rear;
};
struct node {
int vertex;
struct node* next;
};
struct Graph {
int numVertices;
struct node** adjLists;
int* visited;
};
// BFS algorithm
void bfs(struct Graph* graph, int startVertex) {
struct queue* q = createQueue();
graph->visited[startVertex] = 1;
enqueue(q, startVertex);
while (!isEmpty(q)) {
printQueue(q);
int currentVertex = dequeue(q);
printf("Visited %d\n", currentVertex);
while (temp) {
int adjVertex = temp->vertex;
if (graph->visited[adjVertex] == 0) {
graph->visited[adjVertex] = 1;
enqueue(q, adjVertex);
}
temp = temp->next;
}
}
}
// Creating a node
struct node* createNode(int v) {
struct node* newNode = malloc(sizeof(struct node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}
// Creating a graph
struct Graph* createGraph(int vertices) {
struct Graph* graph = malloc(sizeof(struct Graph));
graph->numVertices = vertices;
int i;
for (i = 0; i < vertices; i++) {
graph->adjLists[i] = NULL;
graph->visited[i] = 0;
}
return graph;
}
// Add edge
void addEdge(struct Graph* graph, int src, int dest) {
// Add edge from src to dest
struct node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;
// Create a queue
struct queue* createQueue() {
struct queue* q = malloc(sizeof(struct queue));
q->front = -1;
q->rear = -1;
return q;
}
if (isEmpty(q)) {
printf("Queue is empty");
} else {
printf("\nQueue contains \n");
for (i = q->front; i < q->rear + 1; i++) {
printf("%d ", q->items[i]);
}
}
}
int main() {
struct Graph* graph = createGraph(6);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 2);
addEdge(graph, 1, 4);
addEdge(graph, 1, 3);
addEdge(graph, 2, 4);
addEdge(graph, 3, 4);
bfs(graph, 0);
return 0;
}
OUTPUT:
Queue contains
0 Resetting queue Visited 0
Queue contains
2 1 Visited 2
Queue contains
1 4 Visited 1
Queue contains
4 3 Visited 4
Queue contains
3 Resetting queue Visited 3
TASK 8: Sorting
#include <stdio.h>
// Compare key with each element on the left of it until an element smaller than
// it is found.
// For descending order, change key<array[j] to key>array[j].
while (key < array[j] && j >= 0) {
array[j + 1] = array[j];
--j;
}
array[j + 1] = key;
}
}
// Driver code
int main() {
int data[] = {9, 5, 1, 4, 3};
int size = sizeof(data) / sizeof(data[0]);
insertionSort(data, size);
printf("Sorted array in ascending order:\n");
printArray(data, size);
}
Output:
#include <stdio.h>
#define max 10
int a[11] = { 10, 14, 19, 26, 27, 31, 33, 35, 42, 44, 0 };
int b[10];
for(l1 = low, l2 = mid + 1, i = low; l1 <= mid && l2 <= high; i++) {
if(a[l1] <= a[l2])
b[i] = a[l1++];
else
b[i] = a[l2++];
}
int main() {
int i;
sort(0, max);
Output:
0 10 14 19 26 27 31 33 35 42 44
#include <stdio.h>
// main function
int main() {
int data[] = {8, 7, 2, 1, 0, 9, 6};
printf("Unsorted Array\n");
printArray(data, n);
Output:
Unsorted Array
8 7 2 1 0 9 6
Sorted array in ascending order:
0 1 2 6 7 8 9
#include <stdio.h>
// print array
void printArray(int array[], int size) {
int i;
for ( i = 0; i < size; ++i) {
printf("%d ", array[i]);
}
printf("\n");
}
int main() {
int data[] = {-2, 45, 0, 11, -9};
bubbleSort(data, size);
Output:
Sorted Array in Ascending Order:
-9 -2 0 11 45
#include <stdio.h>
// Using counting sort to sort the elements in the basis of significant places
void countingSort(int array[], int size, int place) {
int output[size + 1],i;
int max = (array[0] / place) % 10;
// Print an array
void printArray(int array[], int size) {
int i;
for ( i = 0; i < size; ++i) {
printf("%d ", array[i]);
}
printf("\n");
}
// Driver code
int main() {
int array[] = {121, 432, 564, 23, 1, 45, 788};
int n = sizeof(array) / sizeof(array[0]);
radixsort(array, n);
printArray(array, n);
}
Output:
TASK 9: Searching
PROBLEM 1:linear search
#include <stdio.h>
int main() {
int array[] = {2, 4, 0, 1, 9};
int x = 1;
int n = sizeof(array) / sizeof(array[0]);
(result == -1) ? printf("Element not found") : printf("Element found at index: %d", result);
}
Output:
PROBLEM 2:
#include <stdio.h>
if (array[mid] == x)
return mid;
if (array[mid] < x)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
int main(void) {
int array[] = {3, 4, 5, 6, 7, 8, 9};
int n = sizeof(array) / sizeof(array[0]);
int x = 4;
int result = binarySearch(array, x, 0, n - 1);
if (result == -1)
printf("Not found");
else
printf("Element is found at index %d", result);
return 0;
}
Output: