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

ADSA

L

Uploaded by

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

ADSA

L

Uploaded by

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

Ex. No.

: 1 C PROGRAMMING USING ARRAY IMPLEMENTATION OF LIST


Date : ADT
Aim: To write and implement a C program for array implementation of list ADT.

Algorithm:
Step 1: Start
Step 2: Initialize and declare variables using structure and arrays. Define the required size of
header files
Step 3: Enter the operations to perform in list as
1)Create
2)Search
3)Display
4)Exit
Step 4: Based on the operations choosing, the list elements are structured.
Step 5: Stop

Program:
#include<stdio.h>
#include<conio.h>
#define MAX 10
void create();
void search();
void display();
int a,b[20],n,e,i,pos;
void main()
{
int m;
char ch;
do
{
printf("\n main Menu");

Reg. No. 2403921362221024 1|Page


printf("\n 1.Create \n 2.Display \n 3.Search \n 4.Exit \n");
printf("\n Enter your Choice: ");
scanf("%d",&m);
switch(m)
{
case 1:
create();
break;
case 2:
display();
break;
case 3:
search();
break;
case 4:
exit(0);
break;
default:
printf("\n Enter the correct choice: ");
}
printf("\n Do u want to continue: ");
scanf("\n%c", &ch);
}while(ch=='y'||ch=='Y');
getchar();
}
void create()
{
printf("\n Enter the number of nodes: ");
scanf("%d", &n);
for(i=0;i<n;i++)
{

Reg. No. 2403921362221024 2|Page


printf("\n Enter the Element: ",i+1);
scanf("%d", &b[i]);
}
display();
}
void search()
{
int flag=0;
printf("\n Enter the Element to be searched: ");
scanf("%d", &e);
for(i=0;i<n;i++)
{
if(b[i]==e)
{
printf("\n Value is in Position %d ", i+1);
flag=1;
break;
}
}
if (flag==0)
printf("\n Value %d is not in the list!!!!", e);
}
void display()
{
printf("\n The Elements of The list ADT are: ");
for(i=0;i<n;i++)
{
printf("\n%d", b[i]);
}
}

Reg. No. 2403921362221024 3|Page


Output:
main Menu
1.Create
2.Display
3.Search
4.Exit
Enter your Choice: 1
Enter the number of nodes: 3
Enter the Element: 100
Enter the Element: 200
Enter the Element: 300
The Elements of The list ADT are:
100
200
300
Do u want to continue: y
main Menu
1.Create
2.Display
3.Search
4.Exit
Enter your Choice: 3
Enter the Element to be searched: 200
Value is in Position 2
Do u want to continue: y
main Menu
1.Create
2.Display
3.Search
4.Exit
Enter your Choice: 4

Result:
Thus a C program for array implementation of list is executed successfully.

Reg. No. 2403921362221024 4|Page


Ex. No. : 2 C PROGRAMMING USING ARRAY IMPLEMENTATION OF STACK
Date : AND QUEUE ADTS.

Aim: To write and implement a program in C for array implementation of Stack and Queue
ADTs.

Algorithm: Stack
Step 1: Start
Step 2: Checks if the stack is full.
Step 3: If the stack is full, produces an error and exit.
Step 4: For Insertion
If the stack is not full, increments top to point next empty space.
Adds data element to the stack location, where top is pointing.
Step 5: For Deletion
If the stack is not empty, accesses the data element at which top is pointing.
Decreases the value of top by 1.
Step 6: Stop

Program:
#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;
printf("\n Enter the size of STACK[MAX=100]:");
scanf("%d",&n);
printf("\n\t STACK OPERATIONS USING ARRAY");

Reg. No. 2403921362221024 5|Page


printf("\n\t--------------------------------");
printf("\n\t 1.PUSH\n\t 2.POP\n\t 3.DISPLAY\n\t 4.EXIT");
do
{
printf("\n Enter the Choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
push();
break;
}
case 2:
{
pop();
break;
}
case 3:
{
display();
break;
}
case 4:
{
printf("\n\t EXIT POINT ");
break;
}
default:
{
printf ("\n\t Please Enter a Valid Choice(1/2/3/4)");

Reg. No. 2403921362221024 6|Page


}
}
}
while(choice!=4);
return 0;
}
void push()
{
if(top>=n-1)
{
printf("\n\tSTACK is over flow");
}
else
{
printf(" Enter a value to be pushed:");
scanf("%d",&x);
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]);
top--;
}

Reg. No. 2403921362221024 7|Page


}
void display()
{
if(top>=0)
{
printf("\n The elements in STACK \n");
for(i=top; i>=0; i--)
printf("\n%d",stack[i]);
printf("\n Press Next Choice");
}
else
{
printf("\n The STACK is empty");
}
}

Output:
Enter the size of STACK[MAX=100]:10
STACK OPERATIONS USING ARRAY
--------------------------------
1.PUSH
2.POP
3.DISPLAY
4.EXIT
Enter the Choice:1
Enter a value to be pushed:12

Enter the Choice:1


Enter a value to be pushed:24

Enter the Choice:1


Enter a value to be pushed:98

Reg. No. 2403921362221024 8|Page


Enter the Choice:3

The elements in STACK


98
24
12
Press Next Choice
Enter the Choice:2
The popped elements is 98
Enter the Choice:3
The elements in STACK
24
12
Press Next Choice
Enter the Choice:4

EXIT POINT
Algorithm: Queue
Step 1: Start
Step 2: Check if the queue is full.
Step 3: If the queue is full, produce overflow error and exit.
Step 4: For insertion
If the queue is not full, increment rear pointer to point the next empty space.
Add data element to the queue location, where the rear is pointing.
Step 5: For Deletion
If the queue is not empty, access the data where front is pointing.
Increment front pointer to point to the next available data element.
Step 6: Stop

Reg. No. 2403921362221024 9|Page


Program:
#include<stdio.h>
#define n 5
int main()
{
int queue[n],ch=1,front=0,rear=0,i,j=1,x=n;
printf("Queue using Array");
printf("\n1.Insertion \n2.Deletion \n3.Display \n4.Exit");
while(ch)
{
printf("\nEnter the Choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
if(rear==x)
printf("\n Queue is Full");
else
{
printf("\n Enter no %d:",j++);
scanf("%d",&queue[rear++]);
}
break;
case 2:
if(front==rear)
{
printf("\n Queue is empty");
}
else
{
printf("\n Deleted Element is %d",queue[front++]);

Reg. No. 2403921362221024 10 | P a g e


x++;
}
break;
case 3:
printf("\nQueue Elements are:\n ");
if(front==rear)
printf("\n Queue is Empty");
else
{
for(i=front; i<rear; i++)
{
printf("%d",queue[i]);
printf("\n");
}
break;
case 4:
exit(0);
default:
printf("Wrong Choice: please see the options");
}
}
}
return 0;
}

Output:
Queue using Array
1.Insertion
2.Deletion
3.Display
4.Exit

Reg. No. 2403921362221024 11 | P a g e


Enter the Choice:1
Enter no 1:10
Enter the Choice:1
Enter no 2:54
Enter the Choice:1
Enter no 3:98
Enter the Choice:1
Enter no 4:234
Enter the Choice:3
Queue Elements are:
10
54
98
234
Enter the Choice:2
Deleted Element is 10
Enter the Choice:3
Queue Elements are:
54
98
234
Enter the Choice:4

Result:
Thus a C program using array implementation of Stack and Queue ADTs is implemented
successfully.

Reg. No. 2403921362221024 12 | P a g e


Ex. No. : 3 C PROGRAMMING USING LINKED LIST IMPLEMENTATION OF
Date : LIST ADTS

Aim: To write and implement a C program Linked list implementation of List ADTs.

Algorithm: Linked List


Step 1: Start
Step 2: Create a struct Node which has two members: data and next. Next
is a pointer to the next node in the list.
Step 3: Create a struct variable head.
Step 4: Creation of list will add a new node to the list:
Create a new node.
It first checks, whether the head is equal to null which means the list is
empty.
If the list is empty, head will point to the newly added node.
If the list is not empty, the new node will be added to end of the list such
that tail's next will point to a newly added node. This new node will
become the new tail of the list.
Step 5: Searching a element
Traverse through the list till current point to null.
Increment the value of count by 1 for each node encountered in the list.
Step 6: display() will display the nodes present in the list:
Define a node current which will initially point to the head of the list.
Traverse through the list till current points to null.
Display each node by making current to point to node next to it in each
iteration.
Step 7: Stop

Program: Linked List


#include<stdio.h>
#include<conio.h>

Reg. No. 2403921362221024 13 | P a g e


#include<alloc.h>
typedef struct list
{
int data;
struct list*next;
}node;
node *newnode,*temp,*head;

node* getnode()
{
node *n;
n=(node*)malloc(sizeof(node));
n->next=NULL;
return(n);
}

void create()
{
char ch=’y';
head->next=NULL;
do
{
newnode =getnode();
printf(“\n enter the element:”);
scanf(“%d”,&newnode->data);
if(head->next==NULL)
head->next=newnode;
else
temp->next=newnode;
temp=newnode;

Reg. No. 2403921362221024 14 | P a g e


printf(“do u wnt to cont?:”);
ch=getch();
}
while(ch==’y'||ch==’Y');
}

void display()
{
printf(“\n\nthe list is:”);
for(temp=head->next;temp!=NULL;temp=temp->next)
{
printf(“\t%d”,temp->data);
}
getch();
}

void insert()
{
int pos;
temp=head->next;
newnode=getnode();
printf(“\n\nenter the new element & pos element aft to be inserted:”);
scanf(“%d%d”,&newnode->data,&pos);
while(temp->data!=pos&&temp->next!=NULL)
{
temp=temp->next;
}
newnode->next=temp->next;
temp->next=newnode;
printf(“\nnew node inserted…”);
display();

Reg. No. 2403921362221024 15 | P a g e


}

void first()
{
newnode=getnode();
printf(“\nenter the new element:”);
scanf(“%d”,&newnode->data);
newnode->next=head->next;
head->next=newnode;
printf(“\nnew node inserted at first…”);
display();
}

void del()
{
int pos;
node *temp1;
temp=head->next;
printf(“\n enter the pos element:”);
scanf(“%d”,&pos);
temp1=head;
while(temp->data!=pos&&temp->next!=NULL)
{
temp1=temp;
temp=temp->next;
}
temp1->next=temp->next;
free(temp);
printf(“\n\nnode deleted…”);
display();

Reg. No. 2403921362221024 16 | P a g e


}
void search()
{
int pos,i=1;temp=head->next;
printf(“enter the element to be search”);
scanf(“%d”,&pos);
while(temp->next!=NULL&&temp->data!=i)
{
if(temp->data==pos)
{
printf(“\n element at pos %d in the list”,i);
break;
}
else
{
i+=1;
temp=temp->next;
}
}
display();
}

void main()
{
int op;
do
{
clrscr();
printf(“\n\n\t\tlinked list implementation of list”);
printf(“\n1.create\n2.display\n3.insert\n4.insert first\n5.search\n6.delete\n7.exit”);
printf(“\n enter the option:”);

Reg. No. 2403921362221024 17 | P a g e


scanf(“%d”,&op);
switch(op)
{
case 1:
create();
break;
case 2:
display();
break;
case 3:
insert();
break;
case 4:
first();
break;
case 5:
search();
break;
case 6:
del();
break;
}
}
while(op<=6);
}

Result:
Thus a C program using Linked list implementation of List ADTs is implemented successfully.

Reg. No. 2403921362221024 18 | P a g e


Ex. No. : 4
APPLICATIONS OF STACK ADT
Date :

Aim: To write and execute a C program to convert infix to postfix using stack.

Algorithm:
Step 1: Start
Step 2: Push “(“onto Stack, and add “)” to the end of X.
Step 3: Scan X from left to right and repeat Step 3 to 6 for each element of X until
the Stack is empty.
Step 4: If an operand is encountered, add it to Y.
Step 5: If a left parenthesis is encountered, push it onto Stack.
Step 6: If an operator is encountered ,then:
Repeatedly pop from Stack and add to Y each operator (on the top of
Stack) which has the same precedence as or higher precedence than
operator.
Add operator to Stack.
[End of If]
Step 7: If a right parenthesis is encountered ,then:
Repeatedly pop from Stack and add to Y each operator (on the top of
Stack) until a left parenthesis is encountered.
Remove the left Parenthesis.
[End of If]
[End of If]
Step 8: Stop.
Program:
#include<stdio.h>
#include<ctype.h>
char stack[100];
int top = -1;
void push(char x)

Reg. No. 2403921362221024 19 | P a g e


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

Reg. No. 2403921362221024 20 | P a g e


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;
}
Output:
Enter the expression : a+b*c
abc*+
Result:
Thus a C program to convert infix to postfix using stack is implemented successfully.

Reg. No. 2403921362221024 21 | P a g e


Ex. No. : 5 IMPLEMENTATION OF BINARY TREES AND OPERATIONS
Date : OF BINARY TREES

Aim: To write and execute a C program to implement operations in binary trees.

Algorithm:
Step 1: Start
Step 2: Create a Binary Tree.
Step 3: Preorder(tree)
Visit the root.
Traverse the left subtree, i.e., call Preorder(left-subtree)
Traverse the right subtree, i.e., call Preorder(right-subtree)
Step 4: Inorder(tree)
Traverse the left subtree, i.e., call Inorder(left-subtree)
Visit the root.
Traverse the right subtree, i.e., call Inorder(right-subtree)
Step 5: Postorder(tree)
Traverse the left subtree, i.e., call Postorder(left-subtree)
Traverse the right subtree, i.e., call Postorder(right-subtree)
Visit the root.
Step 6: Stop
Program:
// C program for different tree traversals
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node* left;
struct node* right;
};
struct node* newNode(int data)

Reg. No. 2403921362221024 22 | P a g e


{
struct node* node
= (struct node*)malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return (node);
}
void printPostorder(struct node* node)
{
if (node == NULL)
return;
printPostorder(node->left);
printPostorder(node->right);
printf("%d ", node->data);
}
void printInorder(struct node* node)
{
if (node == NULL)
return;
printInorder(node->left);
printf("%d ", node->data);
printInorder(node->right);
}
void printPreorder(struct node* node)
{
if (node == NULL)
return;
printf("%d ", node->data);
printPreorder(node->left);
printPreorder(node->right);

Reg. No. 2403921362221024 23 | P a g e


}
int main()
{
struct node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
printf("\nPreorder traversal of binary tree is \n");
printPreorder(root);
printf("\nInorder traversal of binary tree is \n");
printInorder(root);
printf("\nPostorder traversal of binary tree is \n");
printPostorder(root);
getchar();
return 0;
}
Output:
Preorder traversal of binary tree is
12453
Inorder traversal of binary tree is
42513
Postorder traversal of binary tree is
45231

Result:
Thus a C program to implement operations in binary trees is implemented successfully.

Reg. No. 2403921362221024 24 | P a g e


Ex. No. : 6
IMPLEMENTATION OF BINARY SEARCH TREES
Date :

Aim: To write and execute a C program for implementation of Binary search trees.

Algorithm:
Step 1: Start
Step 2: Create a root node
Step 3: Starting from the root. Compare the inserting element with root,
if less than root, then recursively call left subtree, else
recursively call right subtree.
Step 4: After reaching the end, just insert that node at left(if less than
current) or else right.
Step 5: Print the inorder elements of the tree
Program:
#include <stdio.h>
#include <stdlib.h>
struct node {
int key;
struct node *left, *right;
};
// create a new BST 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;
}

Reg. No. 2403921362221024 25 | P a g e


// inorder traversal of BST
void inorder(struct node* root)
{
if (root != NULL) {
inorder(root->left);
printf("%d \n", root->key);
inorder(root->right);
}
}

/* to insert a new node with given key in BST */


struct node* insert(struct node* node, int key)
{
if (node == NULL)
return newNode(key);
if (key < node->key)
node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);

return node;
}

// Driver Code
int main()
{
struct node* root = NULL;
root = insert(root, 50);
insert(root, 30);
insert(root, 20);
insert(root, 40);

Reg. No. 2403921362221024 26 | P a g e


insert(root, 70);
insert(root, 60);
insert(root, 80);
inorder(root);
return 0;
}
Output:
20
30
40
50
60
70
80

Result:
Thus a C program for binary search tree implementation is executed successfully.

Reg. No. 2403921362221024 27 | P a g e


Ex. No. : 7
IMPLEMENTATION OF SEARCHING TECHNIQUES
Date :

Aim: To write and execute a program in C for implementing linear search technique.

Algorithm:
Linear_Search(a, n, val) // 'a' is the given array, 'n' is the size of given array, 'val' is the value to s
earch
Step 1: Start
Step 2: set pos = -1 and i = 1
Step 3: repeat step 4 while i <= n
Step 4: if a[i] == val
set pos = i
print pos
go to step 6
[end of if]
set i = i + 1
[end of loop]
Step 5: if pos = -1
print "value is not present in the array "
[end of if]
Step 6: exit
Program:
#include <stdio.h>
int linearSearch(int a[], int n, int val) {
// Going through array sequencially
for (int i = 0; i < n; i++)
{
if (a[i] == val)
return i+1;
}

Reg. No. 2403921362221024 28 | P a g e


return -1;
}
int main() {
int a[] = {70, 40, 30, 11, 57, 41, 25, 14, 52}; // given array
int val = 41; // value to be searched
int n = sizeof(a) / sizeof(a[0]); // size of array
int res = linearSearch(a, n, val); // Store result
printf("The elements of the array are - ");
for (int i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\nElement to be searched is - %d", val);
if (res == -1)
printf("\nElement is not present in the array");
else
printf("\nElement is present at %d position of array", res);
return 0;
}

Output:

Result:
Thus a C program for implementing linear search is executed successfully.

Reg. No. 2403921362221024 29 | P a g e


Ex. No. : 8 IMPLEMENTATION OF SORTING ALGORITHMS:
Date : INSERTION SORT, QUICK SORT, MERGE SORT

Aim: To write a execute C programs for Implementation of Sorting algorithms: Insertion Sort,
Quick Sort, Merge Sort.

Algorithm Insertion Sort:


Step 1 - If the element is the first element, assume that it is already sorted.
Return 1.
Step2 - Pick the next element, and store it separately in a key.
Step3 - Now, compare the key with all elements in the sorted array.
Step 4 - If the element in the sorted array is smaller than the current element, then
move to the next element. Else, shift greater elements in the array towards the
right.
Step 5 - Insert the value.
Step 6 - Repeat until the array is sorted.

Program Insertion Sort:


#include <stdio.h>
void insert(int a[], int n) /* function to sort an aay with insertion sort */
{
int i, j, temp;
for (i = 1; i < n; i++) {
temp = a[i];
j = i - 1;

while(j>=0 && temp <= a[j]) /* Move the elements greater than temp to one pos
ition ahead from their current position*/
{
a[j+1] = a[j];
j = j-1;

Reg. No. 2403921362221024 30 | P a g e


}
a[j+1] = temp;
}
}

void printArr(int a[], int n) /* function to print the array */


{
int i;
for (i = 0; i < n; i++)
printf("%d ", a[i]);
}

int main()
{
int a[] = { 12, 31, 25, 8, 32, 17 };
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");
printArr(a, n);
insert(a, n);
printf("\nAfter sorting array elements are - \n");
printArr(a, n);

return 0;
}

Output:

Reg. No. 2403921362221024 31 | P a g e


Algorithm Quick Sort:
QUICKSORT (array A, start, end)
{
if (start < end)
{
p = partition(A, start, end)
QUICKSORT (A, start, p - 1)
QUICKSORT (A, p + 1, end)
}
}

PARTITION (array A, start, end)


{
pivot = A[end]
i = start-1
for j = start to end -1 {
do if (A[j] < pivot) {
then i = i + 1
swap A[i] with A[j]
}}
swap A[i+1] with A[end]
return i+1
}

Program Quick Sort:


#include <stdio.h>
/* function that consider last element as pivot,
place the pivot at its exact position, and place
smaller elements to left of pivot and greater
elements to right of pivot. */
int partition (int a[], int start, int end)

Reg. No. 2403921362221024 32 | P a g e


{
int pivot = a[end]; // pivot element
int i = (start - 1);

for (int j = start; j <= end - 1; j++)


{
// If current element is smaller than the pivot
if (a[j] < pivot)
{
i++; // increment index of smaller element
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
int t = a[i+1];
a[i+1] = a[end];
a[end] = t;
return (i + 1);
}

/* function to implement quick sort */


void quick(int a[], int start, int end) /* a[] = array to be sorted, start = Starting inde
x, end = Ending index */
{
if (start < end)
{
int p = partition(a, start, end); //p is the partitioning index
quick(a, start, p - 1);
quick(a, p + 1, end);
}

Reg. No. 2403921362221024 33 | P a g e


}

/* function to print an array */


void printArr(int a[], int n)
{
int i;
for (i = 0; i < n; i++)
printf("%d ", a[i]);
}
int main()
{
int a[] = { 24, 9, 29, 14, 19, 27 };
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");
printArr(a, n);
quick(a, 0, n - 1);
printf("\nAfter sorting array elements are - \n");
printArr(a, n);

return 0;
}

Output:

Algorithm Merge Sort:


MERGE_SORT(arr, beg, end)
if beg < end
set mid = (beg + end)/2

Reg. No. 2403921362221024 34 | P a g e


MERGE_SORT(arr, beg, mid)
MERGE_SORT(arr, mid + 1, end)
MERGE (arr, beg, mid, end)
end of if
END MERGE_SORT

Program Merge Sort:


#include <stdio.h>
/* Function to merge the subarrays of a[] */
void merge(int a[], int beg, int mid, int end)
{
int i, j, k;
int n1 = mid - beg + 1;
int n2 = end - mid;

int LeftArray[n1], RightArray[n2]; //temporary arrays

/* copy data to temp arrays */


for (int i = 0; i < n1; i++)
LeftArray[i] = a[beg + i];
for (int j = 0; j < n2; j++)
RightArray[j] = a[mid + 1 + j];

i = 0; /* initial index of first sub-array */


j = 0; /* initial index of second sub-array */
k = beg; /* initial index of merged sub-array */

while (i < n1 && j < n2)


{
if(LeftArray[i] <= RightArray[j])
{

Reg. No. 2403921362221024 35 | P a g e


a[k] = LeftArray[i];
i++;
}
else
{
a[k] = RightArray[j];
j++;
}
k++;
}
while (i<n1)
{
a[k] = LeftArray[i];
i++;
k++;
}
while (j<n2)
{
a[k] = RightArray[j];
j++;
k++;
}
}
void mergeSort(int a[], int beg, int end)
{
if (beg < end)
{
int mid = (beg + end) / 2;
mergeSort(a, beg, mid);
mergeSort(a, mid + 1, end);
merge(a, beg, mid, end);

Reg. No. 2403921362221024 36 | P a g e


}
}
/* Function to print the array */
void printArray(int a[], int n)
{
int i;
for (i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\n");
}
int main()
{
int a[] = { 12, 31, 25, 8, 32, 17, 40, 42 };
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");
printArray(a, n);
mergeSort(a, 0, n - 1);
printf("After sorting array elements are - \n");
printArray(a, n);
return 0;
}

Output:

Result:
Thus a C program for Implementation of Sorting algorithms: Insertion Sort, Quick Sort, Merge
Sort is executed successfully.

Reg. No. 2403921362221024 37 | P a g e


Ex. No. : 9 SPANNING TREE IMPLEMENTATION – PRIM’S
Date : ALGORITHM

Aim: To write and execute C program for Spanning Tree Implementation – Prim’s Algorithm.

Algorithm:

Step 1: Randomly choose any vertex.The vertex connecting to the edge having least weight is
usually selected.
Step 2:
Find all the edges that connect the tree to new vertices.
Find the least weight edge among those edges and include it in the existing tree.
If including that edge creates a cycle, then reject that edge and look for the next least
weight edge.
Step 3: Keep repeating step-02 until all the vertices are included and Minimum Spanning Tree
(MST) is obtained.

Program:
#include<stdio.h>
int a,b,u,v,n,i,j,ne=1;
int visited[10]={0},min,mincost=0,cost[10][10];
void main()
{
printf("n Enter the number of nodes:");
scanf("%d",&n);

Reg. No. 2403921362221024 38 | P a g e


printf("\n Enter the adjacency matrix: ");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
cost[i][j]=999;
}
visited[1]=1;
printf("\n");
while(ne<n)
{
for(i=0,min=999;i<n;i++)
for(j=0;j<n;j++)
if(cost[i][j]<min)
if(visited[i]!=0)
{
min=cost[i][j];
a=u=i;
b=v=j;
}
if(visited[u]==0 || visited[v]==0)
{
printf("\n Edge %d:(%d %d) cost:%d",ne++,a,b,min);
mincost+=min;
visited[b]=1;
}
cost[a][b]=cost[b][a]=999;
}
printf("\n Minimun cost=%d",mincost);
}

Reg. No. 2403921362221024 39 | P a g e


Output:
Enter the number of nodes: 4
Enter the adjacency matrix: 0
5
8
0
5
0
10
15
8
10
0
20
0
15
20
0
Edge 1:(1 0) cost:5
Edge 2:(0 2) cost:8
Edge 3:(1 3) cost:15
Minimun cost=28

Result:
Thus a C program for Implementation of Prim’s Algorithm is executed successfully.

Reg. No. 2403921362221024 40 | P a g e


Ex. No. : 10
SHORTEST PATH ALGORITHMS DIJKSTRA'S ALGORITHM
Date :

Aim: To write and execute C programs for Implementation of Shortest Path Algorithms
Dijkstra's Algorithm.

Algorithm:
Step 1 : Create a set shortPath to store vertices that come in the way of
the shortest path tree.
Step 2 : Initialize all distance values as INFINITE and assign distance
values as 0 for source vertex so that it is picked first.
Step 3 : Loop until all vertices of the graph are in the shortPath.
Step 3.1 : Take a new vertex that is not visited and is nearest.
Step 3.2 : Add this vertex to shortPath.
Step 3.3 : For all adjacent vertices of this vertex update distances. Now check every
adjacent vertex of V, if sum of distance of u and weight of edge is elss the
update it.
Program:
#include <limits.h>
#include <stdio.h>
#define V 9
int minDistance(int dist[], bool sptSet[]) {
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
if (sptSet[v] == false && dist[v] <= min)
min = dist[v], min_index = v;
return min_index;
}
int printSolution(int dist[], int n) {
printf("Vertex Distance from Source ");
for (int i = 0; i < V; i++)

Reg. No. 2403921362221024 41 | P a g e


printf("%d \t %d ", i, dist[i]);
}
void dijkstra(int graph[V][V], int src) {
int dist[V];
bool sptSet[V];
for (int i = 0; i < V; i++)
dist[i] = INT_MAX, sptSet[i] = false;
dist[src] = 0;
for (int count = 0; count < V - 1; count++) {
int u = minDistance(dist, sptSet);
sptSet[u] = true;
for (int v = 0; v < V; 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];
}
printSolution(dist, V);
}
int main() {
int graph[V][V] = { { 0, 6, 0, 0, 0, 0, 0, 8, 0 },
{ 6, 0, 8, 0, 0, 0, 0, 13, 0 },
{ 0, 8, 0, 7, 0, 6, 0, 0, 2 },
{ 0, 0, 7, 0, 9, 14, 0, 0, 0 },
{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },
{ 0, 0, 6, 14, 10, 0, 2, 0, 0 },
{ 0, 0, 0, 0, 0, 2, 0, 1, 6 },
{ 8, 13, 0, 0, 0, 0, 1, 0, 7 },
{ 0, 0, 2, 0, 0, 0, 6, 7, 0 }
};
dijkstra(graph, 0);
return 0;
}

Reg. No. 2403921362221024 42 | P a g e


Output:
Vertex Distance from Source
0 0
1 6
2 14
3 21
4 21
5 11
6 9
7 8
8 15

Result:
Thus a C program for Implementation of Shortest Path Algorithms Dijkstra's Algorithm is
executed successfully.

Reg. No. 2403921362221024 43 | P a g e

You might also like