0% found this document useful (0 votes)
17 views

Task Soln l12

Uploaded by

saigudipati9000
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Task Soln l12

Uploaded by

saigudipati9000
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 70

TASK 1: Array ADT

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>

void printTwoElements(int arr[], int size)


{
int i;
printf("\n The repeating element is");

for (i = 0; i < size; i++) {


if (arr[abs(arr[i]) - 1] > 0)
arr[abs(arr[i]) - 1] = -arr[abs(arr[i]) - 1];
else
printf(" %d ", abs(arr[i]));
}

printf("\nand the missing element is ");


for (i = 0; i < size; i++) {
if (arr[i] > 0)
printf("%d\t", i + 1);
}
}

// Driver code
int main()
{
int arr[] = {1,2,4,6};

int n = sizeof(arr) / sizeof(arr[0]);


printTwoElements(arr, n);
return 0;
}

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;

//Displays original array


printf("Original array: \n");
for(int i = 0; i < length; i++) {
printf("%d ", arr[i]);
}

//Rotate the given array by n times toward left


for(int i = 0; i < n; i++){
int j, first;
//Stores the first element of the array
first = arr[0];

for(j = 0; j < length-1; j++){


//Shift element of array by one
arr[j] = arr[j+1];
}
//First element of array will be added to the end
arr[j] = first;
}

printf("\n");

//Displays resulting array after rotation


printf("Array after left rotation: \n");
for(int i = 0; i < length; i++){
printf("%d ", arr[i]);
}
return 0;
}

TASK 2: Linked List


PROBLEM 1:
You are given a linked list that contains N integers. You have performed the following
reverse operation on the list:
#include<stdio.h>

#include<stdlib.h>

struct node{

int data;

struct node *link;

};

struct node* reverse(struct node* head, struct node* prev)

// Base case

if (head == NULL)

return NULL;
struct node* temp;

struct node* curr;

curr = head;

// Reversing nodes until curr node's value

// turn odd or Linked list is fully traversed

while (curr != NULL && curr->data % 2 == 0) {

temp = curr->link;

curr->link = prev;

prev = curr;

curr = temp;

// If elements were reversed then head

// pointer needs to be changed

if (curr != head) {

head->link = curr;

// Recur for the remaining linked list

curr = reverse(curr, NULL);

return prev;

// Simply iterate over the odd value nodes


else {

head->link = reverse(head->link, head);

return head;

int main(){

int n,Data;

printf("..... Welcome to Linked List Program ....... \n");

printf("Enter number of nodes you want to create: ");

scanf("%d",&n);

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

printf("Enter the data of node %d :",1);

scanf("%d",&Data);

head->data = Data;

head->link = NULL;

struct node *tmp;

tmp = head;

struct node *current;


int i;
for(i=1;i<n;i++){

printf("Enter the data of node %d :",i+1);

scanf("%d",&Data);

current = malloc(sizeof(struct node));

current->data = Data;
current->link = NULL;

tmp->link = current;

tmp = tmp->link;

head = reverse(head,NULL);

// Traversing

printf("....Display..... \n");

struct node *ptr;

ptr = head;

while(ptr != NULL){

printf("Value: %d\n",ptr->data);

ptr = ptr->link;

return 0;

Develop a C Program to implement Doubly Linked List with Following Menu.


 Insert element( if it is first element directly insert it or read the bellow sub Menu and
insert accordingly.)
 At Beginning of Linked List
 At end of Linked List
 In given postion of Linked List. Read the position to insert value.
 Delete given Element from Linked List( Display NULL if no such element found).
 Display elements (Display NULL if no element is present, If elements presents
display elements with space seperated ).
 Reverse Linked List.
 Search element in Linked list( Display NO if no such element present in list, YES if it
found).
 Exit/Return.
#include<stdio.h>
#include<stdlib.h>
struct node
{
struct node *prev;
struct node *next;
int data;
};
struct node *head;
void insertion_beginning();
void insertion_last();
void insertion_specified();
void deletion_beginning();
void deletion_last();
void deletion_specified();
void display();
void search();
void main ()
{
int choice =0;
while(choice != 9)
{
printf("\n*********Main Menu*********\n");
printf("\nChoose one option from the following list ...\n");
printf("\n===============================================\n");
printf("\n1.Insert in begining\n2.Insert at last\n3.Insert at any random location\n4.Delete from
Beginning\n5.Delete from last\n6.Delete the node after the given data\n7.Search\n8.Show\n9.Exit\
n");
printf("\nEnter your choice?\n");
scanf("\n%d",&choice);
switch(choice)
{
case 1:
insertion_beginning();
break;
case 2:
insertion_last();
break;
case 3:
insertion_specified();
break;
case 4:
deletion_beginning();
break;
case 5:
deletion_last();
break;
case 6:
deletion_specified();
break;
case 7:
search();
break;
case 8:
display();
break;
case 9:
exit(0);
break;
default:
printf("Please enter valid choice..");
}
}
}
void insertion_beginning()
{
struct node *ptr;
int item;
ptr = (struct node *)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
{
printf("\nEnter Item value");
scanf("%d",&item);

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

// { Driver Code Starts.

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

if (k==1 && n >= 1)


tail->next = head;
if(isCircular(head))
{
printf("circular");
}
else
{
printf("Not circular");
}
//printf("%d \n", isCircular(head));
}
return 0;
}
}

TASK 3: Stack ADT


PROBLEM 1:
You are given a stack of N integers. In one operation, you can pop an element from the stack.
You need to increment the top element of the stack by 1 after performing
exactly K operations. If the stack becomes empty after performing K operations and there is
no other way for the stack to be non-empty, print -1.

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

void towers(int, char, char, char);

int main()
{
int num;

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


scanf("%d", &num);
printf("The sequence of moves involved in the Tower of Hanoi are :\n");
towers(num, 'A', 'C', 'B');
return 0;
}
void towers(int num, char frompeg, char topeg, char auxpeg)
{
if (num == 1)
{
printf("\n Move disk 1 from peg %c to peg %c", frompeg, topeg);
return;
}
towers(num - 1, frompeg, auxpeg, topeg);
printf("\n Move disk %d from peg %c to peg %c", num, frompeg, topeg);
towers(num - 1, auxpeg, topeg, frompeg);
}
TASK 4: Queue ADT
PROBLEM 1:
To implement a queue using array, create an array arr of size n and take two
variables front and rear both of which will be initialized to 0 which means the queue is
currently empty. Element rear is the index upto which the elements are stored in the array
and front is the index of the first element of the array. Now, some of the implementation of
queue operations are as follows:
 Enqueue:
 Dequeue
 Front
 Display
#include<stdio.h>
#include<stdlib.h>
#define maxsize 5
void insert();
void delete();
void display();
int front = -1, rear = -1;
int queue[maxsize];
void main ()
{
int choice;
while(choice != 4)
{
printf("\n*************************Main Menu*****************************\n");
printf("\n=================================================================\n");
printf("\n1.insert an element\n2.Delete an element\n3.Display the queue\n4.Exit\n");
printf("\nEnter your choice ?");
scanf("%d",&choice);
switch(choice)
{
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
display();
break;
case 4:
exit(0);
break;
default:
printf("\nEnter valid choice??\n");
}
}
}
void insert()
{
int item;
printf("\nEnter the element\n");
scanf("\n%d",&item);
if(rear == maxsize-1)
{
printf("\nOVERFLOW\n");
return;
}
if(front == -1 && rear == -1)
{
front = 0;
rear = 0;
}
else
{
rear = rear+1;
}
queue[rear] = item;
printf("\nValue inserted ");

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

/* Function to initialize top of two stacks*/


void create()
{
top1 = top2 = -1;
}

/* Function to push an element to stack */


void push1(int element)
{
stack1[++top1] = element; // Pushing the element to stack1
}

/* Function to pop element from stack */


int pop1()
{
return(stack1[top1--]); // Pop element from stack1
}

/* Function to push an element on to stack */


void push2(int element)
{
stack2[++top2] = element; // Pushing the element to stack2
}

/* Function to pop an element from stack */


int pop2()
{
return(stack2[top2--]); // pop element from stack2
}

/* Function to enqueue an element into the queue using stack */


void enqueue()
{
int data, i;
printf("Enter the data : ");
scanf("%d", &data);
push1(data); // Push data from stack to the queue
count++;
}

/* Function to dequeue an element from the queue using stack */


void dequeue()
{
int i;
for (i = 0;i <= count;i++)
{
push2(pop1()); // Pop elements from stack1 and push them to stack2
}
pop2(); // Pop the element from stack2 which is the element to be dequeued
count--;
for (i = 0;i <= count;i++)
{
push1(pop2()); // Push back all the elements from stack2 to stack1
}}

/*Function to display the elements in the queue*/


void display()
{
int i;
if(top1 == -1)
{
printf("\nEMPTY QUEUE\n");
}
else
{
printf("\nQUEUE ELEMENTS : ");
for (i = 0;i <= top1;i++)
{
printf(" %d ", stack1[i]);
}
printf("\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;

// Check if the queue is full


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

// Check if the queue is empty


char isEmpty() {
if (front == -1) return 1;
return 0;
}

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

// Display the queue


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

int main() {
// Fails because front = -1
deQueue();

enQueue('a');
enQueue('b');
enQueue('c');
enQueue('d');
enQueue('e');

// Fails to enqueue because front == 0 && rear == SIZE - 1


enQueue('f');

display();
deQueue();

display();
enQueue('g');
display();

// Fails to enqueue because front == rear + 1


enQueue('h');

return 0;
}
##################################################################################

TASK 5: Binary search Tree


Task 5.A:
// Binary Search Tree operations in C

#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);

// Traverse to the right place and insert the node


if (key < node->key)
node->left = insert(node->left, key);
else
node->right = insert(node->right, key);

return node;
}

// Find the inorder successor


struct node *minValueNode(struct node *node) {
struct node *current = node;

// Find the leftmost leaf


while (current && current->left != NULL)
current = current->left;

return current;
}

// Deleting a node
struct node *deleteNode(struct node *root, int key) {
// Return if the tree is empty
if (root == NULL) return root;

// Find the node to be deleted


if (key < root->key)
root->left = deleteNode(root->left, key);
else if (key > root->key)
root->right = deleteNode(root->right, key);

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

// If the node has two children


struct node *temp = minValueNode(root->right);

// Place the inorder successor in position of the node to be deleted


root->key = temp->key;

// Delete the inorder successor


root->right = deleteNode(root->right, temp->key);
}
return root;
}

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

printf("Inorder traversal: ");


inorder(root);

printf("\nAfter deleting 10\n");


root = deleteNode(root, 10);
printf("Inorder traversal: ");
inorder(root);
}

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

// Create a new Node


struct node* createNode(value) {
struct node* newNode = malloc(sizeof(struct node));
newNode->item = value;
newNode->left = NULL;
newNode->right = NULL;

return newNode;
}

// Insert on the left of the node


struct node* insertLeft(struct node* root, int value) {
root->left = createNode(value);
return root->left;
}

// Insert on the right of the node


struct node* insertRight(struct node* root, int value) {
root->right = createNode(value);
return root->right;
}

int main() {
struct node* root = createNode(1);
insertLeft(root, 12);
insertRight(root, 9);

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

printf("Inorder traversal \n");


inorderTraversal(root);

printf("\nPreorder traversal \n");


preorderTraversal(root);

printf("\nPostorder traversal \n");


postorderTraversal(root);
}
Task 5.C:
ii)without Recursion:
#include<stdio.h>
#include<stdlib.h>
#define bool int

/* A binary tree tNode has data, pointer to left child


and a pointer to right child */
struct tNode
{
int data;
struct tNode* left;
struct tNode* right;
};

/* Structure of a stack node. Linked List implementation is used for


stack. A stack node contains a pointer to tree node and a pointer to
next stack node */
struct sNode
{
struct tNode *t;
struct sNode *next;
};

/* Stack related functions */


void push(struct sNode** top_ref, struct tNode *t);
struct tNode *pop(struct sNode** top_ref);
bool isEmpty(struct sNode *top);

/* Iterative function for inorder tree traversal */


void inOrder(struct tNode *root)
{
/* set current to root of binary tree */
struct tNode *current = root;
struct sNode *s = NULL; /* Initialize stack s */
bool done = 0;

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

/* we have visited the node and its left subtree.


Now, it's right subtree's turn */
current = current->right;
}
else
done = 1;
}
} /* end of while */
}

/* 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);
}

/* put in the data */


new_tNode->t = t;

/* link the old list off the new tNode */


new_tNode->next = (*top_ref);

/* move the head to point to the new tNode */


(*top_ref) = new_tNode;
}

/* The function returns true if stack is empty, otherwise false */


bool isEmpty(struct sNode *top)
{
return (top == NULL)? 1 : 0;
}
/* Function to pop an item from stack*/
struct tNode *pop(struct sNode** top_ref)
{
struct tNode *res;
struct sNode *top;

/*If sNode is empty then error */


if(isEmpty(*top_ref))
{
printf("Stack Underflow \n");
getchar();
exit(0);
}
else
{
top = *top_ref;
res = top->t;
*top_ref = top->next;
free(top);
return res;
}
}

/* Helper function that allocates a new tNode with the


given data and NULL left and right pointers. */
struct tNode* newtNode(int data)
{
struct tNode* tNode = (struct tNode*)
malloc(sizeof(struct tNode));
tNode->data = data;
tNode->left = NULL;
tNode->right = NULL;

return(tNode);
}

/* Driver program to test above functions*/


int main()
{

/* Constructed binary tree is


1
/\
2 3
/\
4 5
*/
struct tNode *root = newtNode(1);
root->left = newtNode(2);
root->right = newtNode(3);
root->left->left = newtNode(4);
root->left->right = newtNode(5);

inOrder(root);

getchar();
return 0;
}

Task 5.D:
#include <stdio.h>
#include <stdlib.h>

//Represent a node of binary tree


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

//Represent the root of binary tree


struct node *root = NULL;

//createNode() will create a new node


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

return newNode;
}

//findHeight() will determine the maximum height of the binary tree


int findHeight(struct node *temp){
//Check whether tree is empty
if(root == NULL) {
printf("Tree is empty\n");
return 0;
}
else {
int leftHeight = 0, rightHeight = 0;

//Calculate the height of left subtree


if(temp->left != NULL)
leftHeight = findHeight(temp->left);

//Calculate the height of right subtree


if(temp->right != NULL)
rightHeight = findHeight(temp->right);

//Compare height of left subtree and right subtree


//and store maximum of two in variable max
int max = (leftHeight > rightHeight) ? leftHeight : rightHeight;

//Calculate the total height of tree by adding height of root


return (max + 1);
}
}

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

//Display the maximum height of the given binary tree


printf("Maximum height of given binary tree: %d", findHeight(root));
return 0;
}

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

/* Creating second Tree. */


struct node *node = createnode(1);
node->right = createnode(2);
node->right->right = createnode(3);
node->right->right->right = createnode(4);
node->right->right->right->right = createnode(5);
/* Sample Tree 2: Right Skewed Tree (Unbalanced).
* 1
* \
* 2
* \
* 3
* \
* 4
* \
* 5
*/
printf("\nInorder traversal of tree 2 :");
inorder(node);
largest(node);
smallest(node);

/* Creating third Tree. */


struct node *root = createnode(15);
/* Sample Tree 3- Tree having just one root node.
* 15
*/
printf("\nInorder traversal of tree 3 :");
inorder(root);
largest(root);
smallest(root);
return 0;
}

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)

printf("\nelement cannot be inserted\n");


}

void display()
{

int i;
printf("\nelements in the hash table are \n");

for(i=0;i< TABLE_SIZE; i++)

printf("\nat index %d \t value = %d",i,h[i]);

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

PROBLEM 2: SEPARATE CHAINING

#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;

printf("Enter the string : ");


//gets(s);
scanf("%s",s);

for(j=0;s[j];j++);
n=j;

printf(" frequency count character in string:\n");

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]);

//Array fr will store frequencies of element


int fr[length];
int visited = -1;

for( i = 0; i < length; i++){


int count = 1;
for(j = i+1; j < length; j++){
if(arr[i] == arr[j]){
count++;
//To avoid counting same element again
fr[j] = visited;
}
}
if(fr[i] != visited)
fr[i] = count;
}

//Displays the frequency of each element present in array


printf("---------------------\n");
printf(" Element | Frequency\n");
printf("---------------------\n");
for(i = 0; i < length; i++){
if(fr[i] != visited){
printf(" %d", arr[i]);
printf(" | ");
printf(" %d\n", fr[i]);
}
}
printf("---------------------\n");
return 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++) {

for (j = 0; j < N + 1; j++) {


Adj[i][j] = 0;
}
}

// Traverse the array of Edges


for ( i = 0; i < M; i++) {

// Find X and Y of Edges


int x = arr[i][0];
int y = arr[i][1];

// Update value to 1
Adj[x][y] = 1;
Adj[y][x] = 1;
}
}

// Function to print the created


// Adjacency Matrix
void printAdjMatrix(int Adj[][N + 1])
{

// Traverse the Adj[][]


int i,j;
for (i = 1; i < N + 1; i++) {
for (j = 1; j < N + 1; j++) {

// Print the value at Adj[i][j]


printf("%d ", Adj[i][j]);
}
printf("\n");
}
}

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

// Function call to create


// Adjacency Matrix
createAdjMatrix(Adj, arr);

// Print Adjacency Matrix


printAdjMatrix(Adj);

return 0;
}

OUTPUT
01001
10100
01000
00001
10010

PROBLEM 2:

#include <limits.h>
#include <stdio.h>
#include <stdbool.h>

// Number of vertices in the graph


#define V 9
int v,i,count;
// A utility function to find the vertex with minimum distance value, from
// the set of vertices not yet included in shortest path tree
int minDistance(int dist[], bool sptSet[])
{
// Initialize min value
int min = INT_MAX, min_index;

for ( v = 0; v < V; v++)


if (sptSet[v] == false && dist[v] <= min)
min = dist[v], min_index = v;

return min_index;
}

// A utility function to print the constructed distance array


void printSolution(int dist[])
{
printf("Vertex \t\t Distance from Source\n");
for (i = 0; i < V; i++)
printf("%d \t\t %d\n", i, dist[i]);
}

// Function that implements Dijkstra's single source shortest path algorithm


// for a graph represented using adjacency matrix representation
void dijkstra(int graph[V][V], int src)
{
int dist[V]; // The output array. dist[i] will hold the shortest
// distance from src to i

bool sptSet[V]; // sptSet[i] will be true if vertex i is included in shortest


// path tree or shortest distance from src to i is finalized

// Initialize all distances as INFINITE and stpSet[] as false


for ( i = 0; i < V; i++)
dist[i] = INT_MAX, sptSet[i] = false;

// Distance of source vertex from itself is always 0


dist[src] = 0;

// Find shortest path for all vertices


for (count = 0; count < V - 1; count++) {
// Pick the minimum distance vertex from the set of vertices not
// yet processed. u is always equal to src in the first iteration.
int u = minDistance(dist, sptSet);

// Mark the picked vertex as processed


sptSet[u] = true;

// Update dist value of the adjacent vertices of the picked vertex.


for (v = 0; v < V; v++)

// Update dist[v] only if is not in sptSet, there is an edge from


// u to v, and total weight of path from src to v through u is
// smaller than current value of dist[v]
if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX
&& dist[u] + graph[u][v] < dist[v])
dist[v] = dist[u] + graph[u][v];
}
// print the constructed distance array
printSolution(dist);
}

// driver program to test above function


int main()
{

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:

Vertex Distance from Source


0 0
1 4
2 12
3 19
4 21
5 11
6 9
7 8
8 14

PROBLEM 3:
// Prim's Algorithm in C

#include<stdio.h>
#include<stdbool.h>

#define INF 9999999

// number of vertices in graph


#define V 5

// create a 2d array of size 5x5


//for adjacency matrix to represent graph
int G[V][V] = {
{0, 9, 75, 0, 0},
{9, 0, 95, 19, 42},
{75, 95, 0, 51, 66},
{0, 19, 51, 0, 31},
{0, 42, 66, 31, 0}};

int main() {
int no_edge; // number of edge

// create a array to track selected vertex


// selected will become true otherwise false
int selected[V];

// set selected false initially


memset(selected, false, sizeof(selected));

// set number of edge to 0


no_edge = 0;

// the number of egde in minimum spanning tree will be


// always less than (V -1), where V is number of vertices in
//graph

// choose 0th vertex and make it true


selected[0] = true;

int x; // row number


int y; // col number

// print for edge and weight


printf("Edge : Weight\n");

while (no_edge < V - 1) {


//For every vertex in the set S, find the all adjacent vertices
// , calculate the distance from the vertex selected at step 1.
// if the vertex is already in the set S, discard it otherwise
//choose another vertex nearest to selected vertex at step 1.

int min = INF;


x = 0;
y = 0;
int i,j;
for (i = 0; i < V; i++) {
if (selected[i]) {
for (j = 0; j < V; j++) {
if (!selected[j] && G[i][j]) { // not in selected and there is an edge
if (min > G[i][j]) {
min = G[i][j];
x = i;
y = j;
}
}
}
}
}
printf("%d - %d : %d\n", x, y, G[x][y]);
selected[y] = true;
no_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

typedef struct edge {


int u, v, w;
} edge;

typedef struct edge_list {


edge data[MAX];
int n;
} edge_list;

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();

// Applying Krushkal Algo


void kruskalAlgo() {
int belongs[MAX], i, j, cno1, cno2;
elist.n = 0;

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


for (j = 0; j < i; j++) {
if (Graph[i][j] != 0) {
elist.data[elist.n].u = i;
elist.data[elist.n].v = j;
elist.data[elist.n].w = Graph[i][j];
elist.n++;
}
}

sort();

for (i = 0; i < n; i++)


belongs[i] = i;

spanlist.n = 0;

for (i = 0; i < elist.n; i++) {


cno1 = find(belongs, elist.data[i].u);
cno2 = find(belongs, elist.data[i].v);

if (cno1 != cno2) {
spanlist.data[spanlist.n] = elist.data[i];
spanlist.n = spanlist.n + 1;
applyUnion(belongs, cno1, cno2);
}
}
}

int find(int belongs[], int vertexno) {


return (belongs[vertexno]);
}

void applyUnion(int belongs[], int c1, int c2) {


int i;

for (i = 0; i < n; i++)


if (belongs[i] == c2)
belongs[i] = c1;
}

// Sorting algo
void sort() {
int i, j;
edge temp;

for (i = 1; i < elist.n; i++)


for (j = 0; j < elist.n - 1; j++)
if (elist.data[j].w > elist.data[j + 1].w) {
temp = elist.data[j];
elist.data[j] = elist.data[j + 1];
elist.data[j + 1] = temp;
}
}

// Printing the result


void print() {
int i, cost = 0;

for (i = 0; i < spanlist.n; i++) {


printf("\n%d - %d : %d", spanlist.data[i].u, spanlist.data[i].v, spanlist.data[i].w);
cost = cost + spanlist.data[i].w;
}

printf("\nSpanning tree cost: %d", cost);


}

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

Enter the no of vertices:


4
Enter the adjacency matrix:
Enter row 1
0
1
1
0
Enter row 2
0
0
0
1
Enter row 3
0
0
0
1
Enter row 4
0
0
0
0

The topological order is:1 2 3 4

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;

// We need int** to store a two dimensional array.


// Similary, we need struct node** to store an array of Linked lists
struct node** adjLists;
};

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

while (temp != NULL) {


int connectedVertex = temp->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;

graph->adjLists = malloc(vertices * sizeof(struct node*));

graph->visited = malloc(vertices * sizeof(int));

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;

// Add edge from dest to src


newNode = createNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode;
}

// Print the graph


void printGraph(struct Graph* graph) {
int v;
for (v = 0; v < graph->numVertices; v++) {
struct node* temp = graph->adjLists[v];
printf("\n Adjacency list of vertex %d\n ", v);
while (temp) {
printf("%d -> ", temp->vertex);
temp = temp->next;
}
printf("\n");
}
}

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:

Adjacency list of vertex 0


2 -> 1 ->
Adjacency list of vertex 1
2 -> 0 ->

Adjacency list of vertex 2


3 -> 1 -> 0 ->

Adjacency list of vertex 3


2 ->
Visited 2
Visited 3
Visited 1
Visited 0

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 queue* createQueue();


void enqueue(struct queue* q, int);
int dequeue(struct queue* q);
void display(struct queue* q);
int isEmpty(struct queue* q);
void printQueue(struct queue* q);

struct node {
int vertex;
struct node* next;
};

struct node* createNode(int);

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

struct node* temp = graph->adjLists[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;

graph->adjLists = malloc(vertices * sizeof(struct node*));


graph->visited = malloc(vertices * sizeof(int));

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;

// Add edge from dest to src


newNode = createNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode;
}

// Create a queue
struct queue* createQueue() {
struct queue* q = malloc(sizeof(struct queue));
q->front = -1;
q->rear = -1;
return q;
}

// Check if the queue is empty


int isEmpty(struct queue* q) {
if (q->rear == -1)
return 1;
else
return 0;
}

// Adding elements into queue


void enqueue(struct queue* q, int value) {
if (q->rear == SIZE - 1)
printf("\nQueue is Full!!");
else {
if (q->front == -1)
q->front = 0;
q->rear++;
q->items[q->rear] = value;
}
}

// Removing elements from queue


int dequeue(struct queue* q) {
int item;
if (isEmpty(q)) {
printf("Queue is empty");
item = -1;
} else {
item = q->items[q->front];
q->front++;
if (q->front > q->rear) {
printf("Resetting queue ");
q->front = q->rear = -1;
}
}
return item;
}

// Print the queue


void printQueue(struct queue* q) {
int i = q->front;

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

PROBLEM 1:Insertion sort

#include <stdio.h>

// Function to print an array


int i,step;
void printArray(int array[], int size) {
for (i = 0; i < size; i++) {
printf("%d ", array[i]);
}
printf("\n");
}

void insertionSort(int array[], int size) {


for (step = 1; step < size; step++) {
int key = array[step];
int j = step - 1;

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

Sorted array in ascending order:


13459

PROBLEM 2:Merge sort

#include <stdio.h>

#define max 10

int a[11] = { 10, 14, 19, 26, 27, 31, 33, 35, 42, 44, 0 };
int b[10];

void merging(int low, int mid, int high) {


int l1, l2, i;

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++];
}

while(l1 <= mid)


b[i++] = a[l1++];

while(l2 <= high)


b[i++] = a[l2++];

for(i = low; i <= high; i++)


a[i] = b[i];
}

void sort(int low, int high) {


int mid;

if(low < high) {


mid = (low + high) / 2;
sort(low, mid);
sort(mid+1, high);
merging(low, mid, high);
} else {
return;
}
}

int main() {
int i;

printf("List before sorting\n");


for(i = 0; i <= max; i++)
printf("%d ", a[i]);

sort(0, max);

printf("\nList after sorting\n");

for(i = 0; i <= max; i++)


printf("%d ", a[i]);
}

Output:

List before sorting


10 14 19 26 27 31 33 35 42 44 0
List after sorting

0 10 14 19 26 27 31 33 35 42 44

PROBLEM 3: Quick sort

#include <stdio.h>

// function to swap elements


void swap(int *a, int *b) {
int t = *a;
*a = *b;
*b = t;
}

// function to find the partition position


int partition(int array[], int low, int high) {
int j;
// select the rightmost element as pivot
int pivot = array[high];

// pointer for greater element


int i = (low - 1);

// traverse each element of the array


// compare them with the pivot
for ( j = low; j < high; j++) {
if (array[j] <= pivot) {

// if element smaller than pivot is found


// swap it with the greater element pointed by i
i++;
// swap element at i with element at j
swap(&array[i], &array[j]);
}
}

// swap the pivot element with the greater element at i


swap(&array[i + 1], &array[high]);

// return the partition point


return (i + 1);
}

void quickSort(int array[], int low, int high) {


if (low < high) {

// find the pivot element such that


// elements smaller than pivot are on left of pivot
// elements greater than pivot are on right of pivot
int pi = partition(array, low, high);

// recursive call on the left of pivot


quickSort(array, low, pi - 1);

// recursive call on the right of pivot


quickSort(array, pi + 1, high);
}
}

// function to print array elements


void printArray(int array[], int size) {
int i;
for (i = 0; i < size; ++i) {
printf("%d ", array[i]);
}
printf("\n");
}

// main function
int main() {
int data[] = {8, 7, 2, 1, 0, 9, 6};

int n = sizeof(data) / sizeof(data[0]);

printf("Unsorted Array\n");
printArray(data, n);

// perform quicksort on data


quickSort(data, 0, n - 1);

printf("Sorted array in ascending order: \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

PROBLEM 4-Bubble Sort

#include <stdio.h>

// perform the bubble sort


void bubbleSort(int array[], int size) {

// loop to access each array element


int step,i;
for (step = 0; step < size - 1; ++step) {

// loop to compare array elements


for (i = 0; i < size - step - 1; ++i) {

// compare two adjacent elements


// change > to < to sort in descending order
if (array[i] > array[i + 1]) {

// swapping occurs if elements


// are not in the intended order
int temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
}
}
}
}

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

// find the array's length


int size = sizeof(data) / sizeof(data[0]);

bubbleSort(data, size);

printf("Sorted Array in Ascending Order:\n");


printArray(data, size);
}

Output:
Sorted Array in Ascending Order:
-9 -2 0 11 45

PROBLEM 5 Radix Sort

#include <stdio.h>

// Function to get the largest element from an array


int getMax(int array[], int n) {
int max = array[0],i;
for ( i = 1; i < n; i++)
if (array[i] > max)
max = array[i];
return max;
}

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

for (i = 1; i < size; i++) {


if (((array[i] / place) % 10) > max)
max = array[i];
}
int count[max + 1];

for ( i = 0; i < max; ++i)


count[i] = 0;

// Calculate count of elements


for ( i = 0; i < size; i++)
count[(array[i] / place) % 10]++;

// Calculate cumulative count


for ( i = 1; i < 10; i++)
count[i] += count[i - 1];
// Place the elements in sorted order
for ( i = size - 1; i >= 0; i--) {
output[count[(array[i] / place) % 10] - 1] = array[i];
count[(array[i] / place) % 10]--;
}

for ( i = 0; i < size; i++)


array[i] = output[i];
}

// Main function to implement radix sort


void radixsort(int array[], int size) {
// Get maximum element
int place;
int max = getMax(array, size);

// Apply counting sort to sort elements based on place value.


for (place = 1; max / place > 0; place *= 10)
countingSort(array, size, place);
}

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

1 23 45 121 432 564 788

TASK 9: Searching
PROBLEM 1:linear search
#include <stdio.h>

int search(int array[], int n, int x) {


int i;
// Going through array sequencially
for (i = 0; i < n; i++)
if (array[i] == x)
return i;
return -1;
}

int main() {
int array[] = {2, 4, 0, 1, 9};
int x = 1;
int n = sizeof(array) / sizeof(array[0]);

int result = search(array, n, x);

(result == -1) ? printf("Element not found") : printf("Element found at index: %d", result);
}

Output:

Element found at index: 3

PROBLEM 2:

#include <stdio.h>

int binarySearch(int array[], int x, int low, int high) {


// Repeat until the pointers low and high meet each other
while (low <= high) {
int mid = low + (high - low) / 2;

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:

Element is found at index 1

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy