Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
214 views

DS Lab File

The document is a lab record for a course on data structures using C. It contains details of 18 experiments conducted on various data structures like arrays, linked lists, stacks, queues, trees, and sorting algorithms. For each experiment, it lists the objective, program code, inputs/outputs. It also includes indexes of experiments conducted on topics like linear search, matrix multiplication, binary search, array operations, string operations, sparse matrices, linked lists, stacks, queues, binary search trees, and sorting algorithms.

Uploaded by

shivam
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
214 views

DS Lab File

The document is a lab record for a course on data structures using C. It contains details of 18 experiments conducted on various data structures like arrays, linked lists, stacks, queues, trees, and sorting algorithms. For each experiment, it lists the objective, program code, inputs/outputs. It also includes indexes of experiments conducted on topics like linear search, matrix multiplication, binary search, array operations, string operations, sparse matrices, linked lists, stacks, queues, binary search trees, and sorting algorithms.

Uploaded by

shivam
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 124

Lab Record

DATA STRUCTURES USING C (CSIT124)

DEPARTMENT OF INFORMATION TECHNOLOGY


AMITY SCHOOL OF ENGINEERING AND TECHNOLOGY
AMITY UNIVERSITY UTTAR PRADESH

3rd Semester,
July-December 2020

By
Faculty: Name………….
……………. A230……………
B. Tech ……..

1
INDEX
S.no Name of Experiment Page no. Date Teacher’s Remark

1 Linear search on 1-D array 4-6 16/07/20

2 Matrix Multiplication 7-10 16/07/20

3 Binary Search on 1-D array 11-13 23/07/20

4 Array Operations on 1-D 14-21 23/07/20


array

5 String Reversal 22-23 30/07/20

6 String Operations 24-28 30/07/20

7 Implementation of sparse 29-31 06/08/20


matrix

8 Singly Linked List 32-38 13/08/20


operations

9 Doubly Linked List 38-44 20/08/20

10 Circular Linked List 45-55 27/08/20

11 Polynomial Linked List 56-69 04/09/20

12 Stack using Array 70-73 11/09/20

13 Stack using Linked List 74-79 11/09/20

14 Queue using Array 80-85 18/09/20

15 Queue using Linked List 86-92 18/09/20

16 Circular Queue 93-97 25/09/20

17 Binary Search tree and 98-103 02/10/20


various traversals and
operations

18 Bubble Sort 104-105 16/10/20

19 Insertion Sort 106-107 12/10/20

20 Selection Sort 108-109 16/10/20

2
21 Heap Sort 110-112 23/10/20

22 Merge Sort 113-115 23/10/20

23 Quick Sort 116-118 23/10/20

24 Kruskal’s Algorithm 119-121 29/10/20

25 Prim’s Algorithm 122-126 29/10/20

3
Experiment – 1
Objective  Write a program to perform linear search on an 1-D array.

Program :

#include <stdio.h>

#include <cstdlib>

int lsearch(int arr[],int N,int num,int *index)

int flag=0;

for(int i=0; i<N; i++){

if(num==arr[i]){

flag=1;

*index=i;

break;

return flag;

int main(){

int N;

printf("Enter the number of elements you want to have in the array : ");

scanf("%d",&N);

int *arr = (int*)malloc(sizeof(int)*N);

printf("Enter %d Elements\n",N);

for(int i=0; i<N; i++){

4
scanf("%d",&arr[i]);

printf("Enter the element you want to search in the array : ");

int num;

scanf("%d",&num);

int index;

int flag = lsearch(arr,N,num,&index);

if(flag)

printf("Element %d was found at index : %d\n",num,index);

else.

printf("sorry the given element could not be found in array\n");

return 0;

OUTPUT:

5
Experiment – 2
Objective  Write a program to perform matrix multiplication on 2-D arrays by passing the
arrays to a function.
Program:
#include <stdio.h>
void enterData(int first[][10], int second[][10], int row1, int col1, int row2, int col2);
void multiply_Matrices(int first[][10], int second[][10], int multResult[][10], int row11, int col1,
int row2, int col2);
void display_matrix(int mult[][10], int row1, int col2);

int main() {
int first[10][10], second[10][10], mult[10][10], row1, col1, row2, col2;
printf("Enter rows and column for the first matrix: ");
scanf("%d %d", &row1, &col1);
printf("Enter rows and column for the second matrix: ");
scanf("%d %d", &row2, &col2);

while (col1 != row2) {


printf("Error! Enter rows and columns again.\n");
printf("Enter rows and columns for the first matrix: ");
scanf("%d%d", &row1, &col1);
printf("Enter rows and columns for the second matrix: ");
scanf("%d%d", &row2, &col2);
}

enterData(first, second, row1, col1, row2, col2);

multiply_Matrices(first, second, mult, row1, col1, row2, col2);

6
printf("First Matrix: \n");
display_matrix(first,row1,col1);
printf("Second Matrix: \n");
display_matrix(second,row2,col2);
printf("Mutliplied Matrix: \n");
display_matrix(mult, row1, col2);

return 0;
}

void enterData(int first[][10], int second[][10], int row1, int col1, int row2, int col2) {
printf("\nEnter elements of matrix 1:\n");

for (int i = 0; i < row1; ++i) {


for (int j = 0; j < col1; ++j) {
printf("Enter a%d%d: ", i + 1, j + 1);
scanf("%d", &first[i][j]);
}
}
printf("\nEnter elements of matrix 2:\n");

for (int i = 0; i < row2; ++i) {


for (int j = 0; j < col2; ++j) {
printf("Enter b%d%d: ", i + 1, j + 1);
scanf("%d", &second[i][j]);
}
}
}

7
void multiply_Matrices(int first[][10], int second[][10], int mult[][10], int row1, int col1, int
row2, int col2) {
for (int i = 0; i < row1; ++i) {
for (int j = 0; j < col2; ++j) {
mult[i][j] = 0;
}
}

for (int i = 0; i < row1; ++i) {


for (int j = 0; j < col2; ++j) {
for (int k = 0; k < col1; ++k) {
mult[i][j] += first[i][k] * second[k][j];
}
}
}
}

void display_matrix(int mult[][10], int row1, int col2) {

for (int i = 0; i < row1; ++i) {


for (int j = 0; j < col2; ++j) {
printf("%d ", mult[i][j]);
if (j == col2 - 1)
printf("\n");
}
}
}
OUTPUT:
8
9
Experiment – 3
Objective  Write a program to perform binary search on a 1-D array.
Program:
#include <stdio.h>
#include <stdlib.h>
void sort(int *arr,int len);
int search(int *arr, int len, int val);

int main(){
printf("Enter the length of the array: ");
int len;
scanf("%d",&len);
int *arr = (int*)malloc(sizeof(int)*len);
printf("Enter %d elements with space in between : ",len);
for(int i=0; i<len; i++){
scanf("%d",&arr[i]);
}
sort(arr,len);

printf("Enter the value that you want to search in the array: ");
int val;
scanf("%d",&val);
int index=0;
index = search(arr,len,val);
if(index != -1)
printf("The given element was found at index %d in the sorted array\n",index);
else
printf("Sorry, The given element could not be found in the provided array\n");

10
return 0;
}

void sort(int *arr, int len){


for(int i=0; i<len; i++){
for(int j=i+1; j<len; j++){
if(arr[i] > arr[j]){
int temp=arr[j];
arr[j]=arr[i];
arr[i]=temp;
}
}
}
}

int search(int *arr, int len, int x){


int l=0;
int r=len-1;
while (l <= r) {
int m = l + (r - l) / 2;
if (arr[m] == x)
return m;

if (arr[m] < x)
l = m + 1;

11
else
r = m - 1;
}

return -1;
}

Output:

12
Experiment – 4
Objective  Write a program to perform array operations (insertion, deletion, and traversal) on
a 1-D array.
Program:
#include <stdio.h>

int enterdata(int arr[]);


void printoperations();
void print_insert_options();
void traversal(int arr[],int len);
void insertion(int arr[], int x,int pos, int *len);
void deletion(int arr[], int *len);

int main(){
printf("This is a program to perform array operations\n\n");
int arr[50];
int len = enterdata(arr);
int choice;
int loop = 1;
do{
printoperations();
printf("Enter your choice: ");
scanf("%d",&choice);
if(choice == 1){
print_insert_options();
char ch;
printf("Enter your choice: ");
scanf("%d",&ch);

13
int ins;
if(ch=='a' || ch=='A')
{
printf("Enter the element you want to insert in the array: ");
scanf("%d",&ins);
printf("Array before insertion:\n");
traversal(arr,len);
insertion(arr,ins,0,&len);
printf("Array after insertion:\n");
traversal(arr,len);
printf("\n");
}
else if(ch == 'b' || ch == 'B'){
printf("Enter the element you want to insert in the array: ");
scanf("%d",&ins);
printf("Array before insertion:\n");
traversal(arr,len);
insertion(arr,ins,len,&len);
printf("Array after insertion:\n");
traversal(arr,len);
printf("\n");
}
else if(ch == 'c' || ch == 'C'){
printf("Enter the element you want to insert in the array: ");
scanf("%d",&ins);
printf("Enter the index at which you want to enter the element: ");
int pos;
scanf("%d",&pos);

14
printf("Array before insertion:\n");
traversal(arr,len);
insertion(arr,ins,pos,&len);
printf("Array after insertion:\n");
traversal(arr,len);
printf("\n");
}
else if(ch == 'd' || ch == 'D'){
printf("Enter the element you want to insert in the array: ");
scanf("%d",&ins);
printf("Enter the index after which you want to enter the element: ");
int pos;
scanf("%d",&pos);
printf("Array before insertion:\n");
traversal(arr,len);
insertion(arr,ins,pos+1,&len);
printf("Array after insertion:\n");
traversal(arr,len);
printf("\n");
}
else{
printf("Wrong choice \n\n");
}
}
else if(choice == 2){
printf("Array before deletion: \n");
traversal(arr,len);
deletion(arr,&len);

15
printf("Array after deletion:\n");
traversal(arr,len);
printf("\n");
}
else if(choice == 3){
printf("The traversed array is:\n");
traversal(arr,len);
printf("\n");
}
else{
printf("Good bye\n");
break;
}
}while(loop);
}

int enterdata(int arr[]){


printf("Enter the number of elements you want to have in the array: ");
int len;
scanf("%d",&len);
printf("Enter array elements:\n");
for(int i=0; i<len; i++){
printf("Enter arr[%d]: ",i);
scanf("%d",&arr[i]);
}
return len;
}

16
void printoperations(){
printf("Enter 1 to insert an element.\nEnter 2 to delete an element.\nEnter 3 for array
traversal.\nEnter any other number to Exit.\n");
}

void print_insert_options(){
printf("Enter A to insert at the Beginning.\nEnter B to insert at the End.\nEnter C to insert at a
position.\nEnter D to insert after a position.\n");
}
void traversal(int arr[],int len){
for(int i=0; i<len; i++){
printf("%d ",arr[i]);
}
printf("\n");
}

void insertion(int arr[50], int x, int pos, int *len){


if(*len+1 < 50){
for(int i= (*len-1); i>=pos; i--){
arr[i+1]=arr[i];
}
arr[pos]=x;
(*len)++;
printf("Insertion operation successful\n");
}
else
printf("There no more space in the given array\n");
}

17
void deletion(int arr[], int *len){
printf("Enter the position at which you want to perform deletion: ");
int pos;
scanf("%d",&pos);
if(pos <= *len-1){
for(int i=pos; i < *len-1; i++){
arr[i]=arr[i+1];
}
(*len)--;
printf("Deletion operation successful\n");
}
else{
printf("Deletion at a position greater than length is not possible\n");
}
}

Output:

18
19
Experiment – 5
Objective  Write a program to reverse an entered String.
Program:
#include <stdio.h>
#include <cstring>
void Reverse_str(char str[100]){
int len = strlen(str);
int l=len-1;
char ch;
for(int i=0; i<len; i++){
if(l<=i)
break;
else{
ch = str[i];
str[i]=str[l];
str[l]=ch;
}
l--;
}
}

int main(){
printf("This is a program to perform reversal operation on 1-D array\n");
char str[100];
printf("Enter the String : ");
fgets(str,sizeof(str),stdin);
printf("String before reversal is:\n");
puts(str);

20
Reverse_str(str);
printf("\nString after reversal is:");
puts(str);
}
Output:

21
Experiment – 6
Objective  Write a program to perform operations (insertion, deletion and traversal) on
a string.
Program:
#include <stdio.h>
#include <string.h>

void copystr(char str[100], char copy[100]);


void print_ops();
void insertion(char str[100],int *len);
void deletion(char str[100], int *len);
void traversal(char str[100],int len);

int main(){
printf("This is a program to perform various operations on the string\n\n");
char str[100],copy[100];
printf("Enter the string: ");
fgets(str,sizeof(str),stdin);
int len = strlen(str);
int loop=1;
int choice;
do{
print_ops();
printf("Enter your choice: ");
scanf("%d",&choice);
if(choice == 1){
printf("Oringinal String is:\n");
puts(str);

22
copystr(str,copy);
}
else if(choice == 2){
printf("String before insertion:\n");
traversal(str,len);
insertion(str,&len);
printf("String after insertion is:\n");
traversal(str,len);
}
else if(choice == 3){
printf("String before deletion is:\n");
traversal(str,len);
deletion(str,&len);
printf("String after deletion is:\n");
traversal(str,len);
}
else if(choice == 4){
printf("The traversed array is:\n");
traversal(str,len);
}
else{
printf("Good bye");
break;
}
}while(loop);

23
void print_ops(){
printf("Enter 1 to make a copy of the string\nEnter 2 to insert a character in the
String\nEnter 3 to delete a character from the string\nEnter 4 to traverse the string\nEnter any
other number to exit\n");
}

void copystr(char str[100], char copy[100]){


strcpy(copy,str);
printf("The copied string is:\n");
puts(copy);
}

void insertion(char str[100], int *len){


int pos;
char x;
printf("Enter the element to insert: ");
scanf(" %c",&x);
printf("Enter the position at which you want to perform insertion: ");
scanf("%d",&pos);
if(*len+1 < 50){
for(int i= (*len-1); i>=pos; i--){
str[i+1]=str[i];
}
str[pos]=x;
(*len)++;
printf("Insertion operation successful\n");
}
else
printf("There no more space in the given array\n");

24
}

void traversal(char str[100],int len){


for(int i=0; i<len; i++){
printf("%c",str[i]);
}
printf("\n");
}

void deletion(char str[100], int *len){


printf("Enter the position at which you want to perform deletion: ");
int pos;
scanf("%d",&pos);
if(pos <= *len-1){
for(int i=pos; i < *len-1; i++){
str[i]=str[i+1];
}
(*len)--;
printf("Deletion operation successful\n");
}
else{
printf("Deletion at a position greater than length is not possible\n");
}
}
Output:

25
26
Experiment – 7
Objective  Write a program to implement sparse matrix.

Program:

#include <stdio.h>

int main(){

printf("This is the program to implement sparse matrix\n");

int m,n;

printf("\nEnter the number of rows and columns with a space between them: ");

scanf("%d %d",&m,&n);

int matrix[m][n];

int sparse[3][n];

int c=0;

printf("\nEnter the matrix Elements:\n");

for(int i=0; i<m; i++){

for(int j=0; j<n; j++){

scanf("%d",&matrix[i][j]);

if(matrix[i][j] != 0)

sparse[0][c]=i;

sparse[1][c]=j;

sparse[2][c]=matrix[i][j];

c++;

27
printf("\nOriginal Matrix:\n");

for(int i=0; i<m; i++){

for(int j=0; j<n; j++){

printf("%d ",matrix[i][j]);

printf("\n");

printf("Sparse Matrix:\n");

for(int i=0; i<3; i++){

for(int j=0; j<c; j++){

printf("%d ",sparse[i][j]);

printf("\n");

int sp=0;

printf("\nPrinting matrix using sparse matrix:\n");

for(int i=0; i<m; i++){

for(int j=0; j<n; j++){

if(sparse[0][sp]==i && sparse[1][sp]==j){

printf("%d ",sparse[2][sp]);

sp++;

else

printf("0 ");

28
}

printf("\n");

return 0;

Output:

29
Experiment – 8
Objective  Write a program to perform insertion on linked list.
Program:
#include <stdio.h>
#include <stdlib.h>

struct Node { 
    int data; 
    Node* next; 
}; 

static void reverse(struct Node** head_ref) 

    struct Node* prev = NULL; 
    struct Node* current = *head_ref; 
    struct Node* next = NULL; 
    while (current != NULL) { 
        next = current->next; 
        current->next = prev; 
        prev = current; 
        current = next; 
    } 
    *head_ref = prev; 

int getCount(Node* head)  
{  
    int count = 0;

30
    Node* current = head;  
    while (current != NULL)  
    {  
        count++;  
        current = current->next;  
    }  
    return count;  
}  

int search(Node* head, int x)  
{  
    Node* current = head;   
    while (current != NULL)  
    {  
        if (current->data == x)  
            return 1;  
        current = current->next;  
    }  
    return 0;  
}  

void deleteNode(struct Node **head_ref, int key) 
{  
    struct Node* temp = *head_ref, *prev; 
    if (temp != NULL && temp->data == key) 
    { 
        *head_ref = temp->next;   
        free(temp);               

31
        return; 
    } 
    while (temp != NULL && temp->data != key) 
    { 
        prev = temp; 
        temp = temp->next; 
    } 
    if (temp == NULL) return;  
    prev->next = temp->next; 
  
    free(temp);

void append(struct Node** head_ref, int new_data) 

    struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); 
    struct Node *last = *head_ref; 
    new_node->data  = new_data; 
    new_node->next = NULL; 
    if (*head_ref == NULL) 
    { 
       *head_ref = new_node; 
       return; 
    }   
    while (last->next != NULL) 
        last = last->next; 
    last->next = new_node; 
    return;     

32
void push(struct Node** root, int new_data) 

    struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); 
    new_node->data  = new_data; 
    new_node->next = (*root); 
    (*root)    = new_node; 

 
void insert(Node** root, int item) 

    Node* temp = new Node; 
    Node* ptr; 
    temp->data = item; 
    temp->next = NULL; 

    if (*root == NULL) 
        *root = temp; 
    else { 
        ptr = *root; 
        while (ptr->next != NULL) 
            ptr = ptr->next; 
        ptr->next = temp; 
    } 

void display(Node* root) 

33
    while (root != NULL) { 
        printf("%d ",root->data);
        root = root->next; 
    } 
    printf("\n");

int main() 

    Node *root = NULL;
    int n;
    printf("Enter the number of elements you want enter:");
    scanf("%d",&n);
    printf("Enter %d elements:\n",n);
    int num;
    for (int i = 0; i < n; i++){
        scanf("%d",&num);
        insert(&root, num); 
    }
    int choice;
    do {
    printf("Enter \n1 to perform insertion a linked list\n2 for deletion\n3 for display\n4 to c
ount the number of nodes\n5 to search a value\n6 to reverse cotent of the linked list\nAny other n
umber to exit");
    printf("\nEnter your choice : ");
    scanf("%d",&choice);
    if(choice == 1){
        char ch;

34
        printf("\nEnter A to insert at the beginning\nEnter B to insert at the last\nEnter C to i
nsert at the middle\n");
        printf("Enter your choice : ");
        scanf(" %c",&ch);
        if(ch == 'A' || ch == 'a'){
            printf("List before insertion is:\n");
            display(root);
            printf("Enter the element you want to insert at the beginning of the linked list: ");
            int new_data;
            scanf("%d",&new_data);
            push(&root,new_data);
            printf("List after insertion is:\n");
            display(root);
        }
        if(ch == 'B' || ch == 'b'){
            printf("List before insertion is:\n");
            display(root);
            printf("Enter the element you want to insert at the last of the linked list: ");
             int new_data;
            scanf("%d",&new_data);
            append(&root,new_data);
            printf("List after insertion is:\n");
            display(root);
        }
    }
    else if(choice == 2){
        printf("List before deletion is:\n");
        display(root);
        printf("Enter the element you want to delete in the linked list: ");
35
        int new_data;
        scanf("%d",&new_data);
        deleteNode(&root,new_data);
        printf("List after insertion is:\n");
        display(root);
    }
    else if(choice == 3){
        printf("The elements of linked list are:\n");
        display(root);
    }
    else if(choice == 4){
        int len=getCount(root);
        printf("The number of nodes in current linked list = %d\n",len);
    }
    else if(choice == 5){
        printf("Enter the element you want to search in the linked list: ");
        int x;
        scanf("%d",&x);
        int result = search(root,x);
        if(result)
            printf("Element found\n");
        else 
            printf("Element not found\n");
    }
    else if(choice == 6){
        printf("Linked list before reversal:\n");
        display(root);
        reverse(&root);

36
        printf("Linked list after reversal:\n");
        display(root);
    }
    else{
        printf("GOOdbye\n");
        break;
    }
    }while(choice);
    return 0; 
}
Output:

37
Experiment – 9
Objective – Write a program to perform various operations on Doubly linked list.
Program:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

struct node{
struct node *prev;
int data;
struct node *next;
};

int count(struct node *p){


int c=0;
while(p != NULL){
c++;
p=p->next;
}
return c;
}

struct node *newnode(int val){


struct node *temp=(struct node*)malloc(sizeof(struct node));
temp->data=val;
temp->next=NULL;
temp->prev=NULL;
return temp;

38
}

void insert_mid(struct node **head){


printf("\nEnter the data for node: ");
int val,i;
scanf("%d",&val);
struct node *temp=newnode(val);
int mid=count(*head)/2;
struct node *p=*head;
for(i=0; i<mid; i++)
p=p->next;
temp->next=p->next;
temp->prev=p;
p->next=temp;
}

void insert_first(struct node **head){


printf("\nEnter the data for node: ");
int val;
scanf("%d",&val);
struct node *temp=newnode(val);
temp->prev=NULL;
temp->next=*head;
*head=temp;
}

void insert_last(struct node **head){


printf("\nEnter the data for node: ");

39
int val;
scanf("%d",&val);
struct node* temp=newnode(val);
if(*head==NULL){
*head=temp;
}
else{
struct node *p=*head;
while(p->next != NULL)
p=p->next;
temp->prev=p;
p->next=temp;
}
}

void create(struct node **head){


int num;
printf("Enter the elements you want to have in the linked list: ");
scanf("%d",&num);
for(int i=0; i<num; i++)
insert_last(head);
}

void display(struct node *p){


printf("\nDisplaying current list:\n");
while(p!=NULL){
printf("%d --> ",p->data);
p=p->next;

40
}
printf("NULL\n");
}

int search(struct node *p){


int key;
printf("Enter the key to search for: ");
scanf("%d",&key);
while(p != NULL){
if(p->data == key){
printf("Key was found\n");
return 1;
}
p=p->next;
}
printf("Key was found\n");
return 0;
}

void del(struct node **head){


int key;
printf("Enter the key you want to delete: ");
scanf("%d",&key);
struct node *p=*head;
if(p->data == key){
*head=(*head)->next;
free(p);
return;

41
}
while(p != NULL){
if(p->data == key){
p->prev->next=p->next;
p->next->prev=p->prev;
free(p);
break;
}
p=p->next;
}
}

void print_menu(){
printf("\nMenu:\n");
printf("Enter 1 to insert at first\nEnter 2 to to insert at mid\nEnter 3 to insert at
last\n");
printf("Enter 4 to display\nEnter 5 to search\nEnter the 6 to delete a node\nEnter
10 to print menu\nEnter 0 exit\n");
}

int main(){
struct node *head=NULL;
printf("This is the program to perform various operations on linked list\n\n");
create(&head);
print_menu();
int choice;
printf("Enter your choice: ");
scanf("%d",&choice);
do{

42
if(choice==1)
insert_first(&head);
else if(choice==2)
insert_mid(&head);
else if(choice==3)
insert_last(&head);
else if(choice==4)
display(head);
else if(choice==5)
search(head);
else if(choice==6)
del(&head);
else if(choice==10)
print_menu();
else if(choice==0)
break;
printf("Enter your choice: ");
scanf("%d",&choice);
}while(choice != 0);
return 0;
}
Output:

43
44
Experiment 10
Objective – Write a program to perform various operations on circular linked list.

Program:

#include<stdio.h>

#include<stdlib.h>

struct node

int data;

struct node *next;

};

struct node *head;

void beginsert ();

void lastinsert ();

void randominsert();

void begin_delete();

void last_delete();

void random_delete();

void display();

void search();

void print_menu();

int main ()

int choice =0;

print_menu();

45
while(choice != 7)

printf("\nEnter your choice?\n");

scanf("\n%d",&choice);

switch(choice)

case 1:

beginsert();

break;

case 2:

lastinsert();

break;

case 3:

begin_delete();

break;

case 4:

last_delete();

break;

case 5:

search();

break;

case 6:

display();

break;

case 7:

46
print_menu();

case 8:

exit(0);

break;

default:

printf("Please enter valid choice..");

void beginsert()

struct node *ptr,*temp;

int item;

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

if(ptr == NULL)

printf("\nOVERFLOW");

else

printf("\nEnter the node data?");

scanf("%d",&item);

ptr -> data = item;

if(head == NULL)

47
head = ptr;

ptr -> next = head;

else

temp = head;

while(temp->next != head)

temp = temp->next;

ptr->next = head;

temp -> next = ptr;

head = ptr;

printf("\nnode inserted\n");

void lastinsert()

struct node *ptr,*temp;

int item;

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

if(ptr == NULL)

printf("\nOVERFLOW\n");

48
else

printf("\nEnter Data?");

scanf("%d",&item);

ptr->data = item;

if(head == NULL)

head = ptr;

ptr -> next = head;

else

temp = head;

while(temp -> next != head)

temp = temp -> next;

temp -> next = ptr;

ptr -> next = head;

printf("\nnode inserted\n");

49
void begin_delete()

struct node *ptr;

if(head == NULL)

printf("\nUNDERFLOW");

else if(head->next == head)

head = NULL;

free(head);

printf("\nnode deleted\n");

else

{ ptr = head;

while(ptr -> next != head)

ptr = ptr -> next;

ptr->next = head->next;

free(head);

head = ptr->next;

printf("\nnode deleted\n");

50
}

void last_delete()

struct node *ptr, *preptr;

if(head==NULL)

printf("\nUNDERFLOW");

else if (head ->next == head)

head = NULL;

free(head);

printf("\nnode deleted\n");

else

ptr = head;

while(ptr ->next != head)

preptr=ptr;

ptr = ptr->next;

preptr->next = ptr -> next;

free(ptr);

51
printf("\nnode deleted\n");

void search()

struct node *ptr;

int item,i=0,flag=1;

ptr = head;

if(ptr == NULL)

printf("\nEmpty List\n");

else

printf("\nEnter item which you want to search?\n");

scanf("%d",&item);

if(head ->data == item)

printf("item found at location %d",i+1);

flag=0;

else

52
while (ptr->next != head)

if(ptr->data == item)

printf("item found at location %d ",i+1);

flag=0;

break;

else

flag=1;

i++;

ptr = ptr -> next;

if(flag != 0)

printf("Item not found\n");

void display()

53
{

struct node *ptr;

ptr=head;

if(head == NULL)

printf("\nnothing to print");

else

printf("\n printing values ... \n");

while(ptr -> next != head)

printf("%d-->", ptr -> data);

ptr = ptr -> next;

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

void print_menu(){

printf("\n*********Main Menu*********\n");

printf("\nChoose one option from the following list ...\n");

printf("\n===============================================\n");

54
printf("\n1.Insert in begining\n2.Insert at last\n3.Delete from Beginning\n4.Delete from
last\n5.Search for an element\n6.Show\n7.Display menu\n8.Exit\n");

Output:

55
Experiment 11
Objective – Write a program to perform addition, subtraction, and multiplication
operation on a linked list.
Program:
#include <stdio.h>

#include <conio.h>

#include <stdlib.h>

struct node

int num;

int coeff;

struct node *link;

};

struct node *head1;

struct node *head2;

struct node *addResult;

struct node *subResult;

struct node *multResult;

struct node *createPolyLL(struct node *head);

void display(struct node *head);

struct node *append(struct node *head, int num, int coeff);

struct node *addNodes(struct node *head1, struct node *head2, struct node *head3);

struct node *subNodes(struct node *head1, struct node *head2, struct node *head3);

56
struct node *multiplyNodes(struct node *head1, struct node *head2, struct node *head3);

struct node *removeDuplicates(struct node *head1);

void menu()

printf("--- C Program for Polynomial Addition & Subtraction using LL --- \n\n");

printf("Operations: \n");

printf(" Press 0 : For Menu\n");

printf(" Press 1 : To Enter 1st Polynomial Expression\n");

printf(" Press 2 : To Enter 2nd Polynomial Expression\n");

printf(" Press 3 : To Perform Addition\n");

printf(" Press 4 : To Perform Subtraction\n");

printf(" Press 5 : To Perform Multiplication\n");

printf(" Press 9 : To Quit\n");

int main()

int ch;

menu();

while (ch != 9)

printf("\n\n\nEnter a command(0-4 or 9 to quit): ");

scanf("%d", &ch);

57
switch (ch)

case 1:

head1 = createPolyLL(head1);

printf("\n\n=> First Polynomial Expression is: ");

display(head1);

break;

case 2:

head2 = createPolyLL(head2);

printf("\n\n=> Second Polynomial Expression is: ");

display(head2);

break;

case 3:

addResult = addNodes(head1, head2, addResult);

printf("\n\n=> Result of Addition Operation: ");

display(addResult);

break;

case 4:

subResult = subNodes(head1, head2, subResult);

printf("\n\n=> Result of Subtraction Operation: ");

display(subResult);

break;

case 5:

multResult = multiplyNodes(head1, head2, multResult);

printf("\n\n=> Result of Multiplication Operation: ");

58
display(multResult);

break;

case 9:

break;

default:

printf("Invalid input!\n\n");

break;

getch();

return 0;

struct node *createPolyLL(struct node *head)

struct node *newNode, *ptr;

int n, c, s, i = 1;

printf("\nHow many variables you wish to insert? Enter: ");

scanf("%d", &s);

printf("\nEnter the number: ");

scanf("%d", &n);

printf("\nEnter it's Power: ");

scanf("%d", &c);

59
if (head == NULL)

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

newNode->num = n;

newNode->coeff = c;

newNode->link = NULL;

head = newNode;

else

struct node *next = head;

struct node *temp;

while (next != NULL)

temp = next->link;

free(next);

next = temp;

head = NULL;

head = append(head, n, c);

/*ptr = head;

while (ptr->link != NULL)

ptr = ptr->link;

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

newNode->num = n;

60
newNode->coeff = c;

newNode->link = NULL;

ptr->link = newNode;*/

while (i <= s - 1)

printf("\nEnter the number: ");

scanf("%d", &n);

printf("\nEnter it's Power: ");

scanf("%d", &c);

i++;

head = append(head, n, c);

return head;

void display(struct node *head)

struct node *ptr = head;

while (ptr != NULL)

printf("(%d)X^%d", ptr->num, ptr->coeff);

if (ptr->link != NULL)

printf(" + ");

61
ptr = ptr->link;

struct node *append(struct node *head, int num, int coeff)

struct node *newNode, *ptr;

if (head == NULL)

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

newNode->num = num;

newNode->coeff = coeff;

newNode->link = NULL;

head = newNode;

else

ptr = head;

while (ptr->link != NULL)

ptr = ptr->link;

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

newNode->num = num;

newNode->coeff = coeff;

newNode->link = NULL;

ptr->link = newNode;

62
}

return head;

struct node *addNodes(struct node *head1, struct node *head2, struct node *head3)

struct node *ptr1, *ptr2;

ptr1 = head1, ptr2 = head2;

int addNum, coeff;

while (ptr1 != NULL && ptr2 != NULL)

if (ptr1->coeff == ptr2->coeff)

addNum = ptr1->num + ptr2->num;

head3 = append(head3, addNum, ptr1->coeff);

ptr1 = ptr1->link;

ptr2 = ptr2->link;

else if (ptr1->coeff > ptr2->coeff)

head3 = append(head3, ptr1->num, ptr1->coeff);

ptr1 = ptr1->link;

else if (ptr1->coeff < ptr2->coeff)

63
head3 = append(head3, ptr2->num, ptr2->coeff);

ptr2 = ptr2->link;

if (ptr1 == NULL)

while (ptr2 != NULL)

head3 = append(head3, ptr2->num, ptr2->coeff);

ptr2 = ptr2->link;

if (ptr2 == NULL)

while (ptr1 != NULL)

head3 = append(head3, ptr1->num, ptr1->coeff);

ptr1 = ptr1->link;

return head3;

struct node *subNodes(struct node *head1, struct node *head2, struct node *head3)

64
{

struct node *ptr1, *ptr2;

ptr1 = head1, ptr2 = head2;

int addNum, coeff;

while (ptr1 != NULL && ptr2 != NULL)

if (ptr1->coeff == ptr2->coeff)

addNum = ptr1->num - ptr2->num;

head3 = append(head3, addNum, ptr1->coeff);

ptr1 = ptr1->link;

ptr2 = ptr2->link;

else if (ptr1->coeff > ptr2->coeff)

head3 = append(head3, ptr1->num, ptr1->coeff);

ptr1 = ptr1->link;

else if (ptr1->coeff < ptr2->coeff)

head3 = append(head3, ptr2->num, ptr2->coeff);

ptr2 = ptr2->link;

if (ptr1 == NULL)

65
{

while (ptr2 != NULL)

head3 = append(head3, ptr2->num, ptr2->coeff);

ptr2 = ptr2->link;

if (ptr2 == NULL)

while (ptr1 != NULL)

head3 = append(head3, ptr1->num, ptr1->coeff);

ptr1 = ptr1->link;

return head3;

struct node *multiplyNodes(struct node *head1, struct node *head2, struct node *head3)

struct node *ptr1 = head1, *ptr2 = head2;

int multNum, mpower;

while (ptr1 != NULL)

66
while (ptr2 != NULL)

multNum = ptr1->num * ptr2->num;

mpower = ptr1->coeff + ptr2->coeff;

head3 = append(head3, multNum, mpower);

ptr2 = ptr2->link;

ptr2 = head2;

ptr1 = ptr1->link;

removeDuplicates(head3);

return head3;

struct node *removeDuplicates(struct node *head1)

struct node *ptr1, *ptr2, *dup;

ptr1 = head1;

while (ptr1 != NULL && ptr1->link != NULL)

ptr2 = ptr1;

while (ptr2->link != NULL)

if (ptr1->coeff == ptr2->link->coeff)

67
ptr1->num = ptr1->num + ptr2->num;

dup = ptr2->link;

ptr2->link = ptr2->link->link;

free(dup);

else

ptr2 = ptr2->link;

ptr1 = ptr1->link;

return ptr1;

Output:

68
69
Experiment 12
Objective – Write a program to create stack using array and perform various operations
on it.
Programs:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
#define max 20

int top=-1,s[max];
void push(int n)
{
if(top==max-1)
{
puts("stack is over flown");
return;
}
else
{
top=top+1;
s[top]=n;
}
}
void pop()
{
int del;
if(top==-1)

70
{
puts("stack is underflown");
return;
}
else
{
del=s[top];
printf("\n poped element is %d",del);
top=top-1;
}
}
void display()
{
int i;
if(top==-1)
puts("stack is empty");
else
{
for(i=top;i>=0;i--)
printf("\t%d",s[i]);
}
}
void print_menu(){
printf("\n 1.Push");
printf("\n 2.Pop");
printf("\n 3.Display");
printf("\n 4.Print menu");
printf("\n 5.Exit ");

71
}
int main()
{
int opt,n;
print_menu();
do
{
printf("\n\nEnter your choice :: ");
scanf("%d",&opt);
switch(opt)
{
case 1:
printf("\n Enter any element to push :: ");
scanf("%d",&n);
push(n);
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
print_menu();
break;
case 5:
exit(0);
break;

72
}
}
while(1);

return 0;
}
Output:

73
Experiment 13
Objective – Write a program to create a stack using linked list and perform various operations
on it.
Program:
#include <stdio.h>
#include <stdlib.h>
void push();
void pop();
void display();
void display_menu();
struct node
{
int val;
struct node *next;
};
struct node *head;

int main ()
{
int choice=0;
printf("\n*********Stack operations using linked list*********\n");
printf("\n----------------------------------------------\n");
display_menu();
while(choice != 5)
{
printf("\nEnter your choice : ");
scanf("%d",&choice);
switch(choice)

74
{
case 1:
{
push();
break;
}
case 2:
{
pop();
break;
}
case 3:
{
display();
break;
}
case 4:
{
display_menu();
break;
}
case 5:
{
printf("Exiting....");
break;
}
default:
{

75
printf("Please Enter valid choice ");
}
};
}
}
void push ()
{
int val;
struct node *ptr = (struct node*)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("not able to push the element");
}
else
{
printf("Enter the value: ");
scanf("%d",&val);
if(head==NULL)
{
ptr->val = val;
ptr -> next = NULL;
head=ptr;
}
else
{
ptr->val = val;
ptr->next = head;
head=ptr;

76
}
printf("Item pushed");

}
}

void pop()
{
int item;
struct node *ptr;
if (head == NULL)
{
printf("Underflow");
}
else
{
item = head->val;
ptr = head;
head = head->next;
free(ptr);
printf("Item popped");

}
}
void display()
{
int i;

77
struct node *ptr;
ptr=head;
if(ptr == NULL)
{
printf("Stack is empty\n");
}
else
{
printf("Printing Stack elements \n");
while(ptr!=NULL)
{
printf("%d ",ptr->val);
ptr = ptr->next;
}
}
}

void display_menu(){
printf("\n\nChose one from the below options...\n");
printf("\n1.Push\n2.Pop\n3.Show\n4.Print menu\n5.Exit");
}
Output:

78
79
Experiment 14
Objective – Write a program to create queue using array and perform various queue operations.
Program:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#define MAX 10

int queue_arr[MAX];
int rear=-1;
int front=-1;

void insert(int item);


int del();
int peek();
void display();
int isFull();
int isEmpty();
void display_menu();

int main()
{
int choice,item;
display_menu();
while(choice != 6)
{
printf("\nEnter your choice : ");
scanf("%d",&choice);

80
switch(choice)
{
case 1:
printf("\nInput the element for adding in queue : ");
scanf("%d",&item);
insert(item);
break;
case 2:
item=del();
if(item != -1)
printf("\nDeleted element is %d\n",item);
break;
case 3:
printf("\nElement at the front is %d\n",peek());
break;
case 4:
display();
break;
case 5:
display_menu();
break;
case 6:
break;
default:
printf("\nWrong choice\n");
}
}
getch();

81
return 0;

void insert(int item)


{
if( isFull() )
{
printf("\nQueue Overflow\n");
return;
}
if( front == -1 )
front=0;
rear=rear+1;
queue_arr[rear]=item ;
}

int del()
{
int item;
if( isEmpty() )
{
printf("\nQueue Underflow\n");
return -1;
}
item=queue_arr[front];
front=front+1;
return item;

82
}

int peek()
{
if( isEmpty() )
{
printf("\nQueue Underflow\n");
exit(1);
}
return queue_arr[front];
}

int isEmpty()
{
if( front==-1 || front==rear+1 )
return 1;
else
return 0;
}

int isFull()
{
if( rear==MAX-1 )
return 1;
else
return 0;
}

83
void display()
{
int i;
if ( isEmpty() )
{
printf("\nQueue is empty\n");
return;
}
printf("\nQueue is :\n\n");
for(i=front;i<=rear;i++)
printf("%d ",queue_arr[i]);
printf("\n\n");
}

void display_menu(){
printf("\n1.Insert\n");
printf("2.Delete\n");
printf("3.Display element at the front\n");
printf("4.Display all elements of the queue\n");
printf("5.Display menu\n");
printf("6.Quit\n");
}
Output:

84
85
Experiment 15
Objective – Write a program to implement queue using linked list and perform its various
operations.
Program:
#include <stdio.h>
#include <stdlib.h>

struct node
{
int info;
struct node *ptr;
}*front,*rear,*temp,*front1;

int frontelement();
void enq(int data);
void deq();
void empty();
void display();
void create();
void queuesize();

int count = 0;

int main()
{
int no, ch, e;
printf("\n ------------Menu-----------");
printf("\n 1 - Enque");
printf("\n 2 - Deque");
86
printf("\n 3 - Front element");
printf("\n 4 - Empty");
printf("\n 5 - Exit");
printf("\n 6 - Display");
printf("\n 7 - Queue size");
create();
while (1)
{
printf("\n Enter choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("Enter data : ");
scanf("%d", &no);
enq(no);
break;
case 2:
deq();
break;
case 3:
e = frontelement();
if (e != 0)
printf("Front element : %d", e);
else
printf("\n No front element in Queue as queue is empty");
break;
case 4:

87
empty();
break;
case 5:
exit(0);
case 6:
display();
break;
case 7:
queuesize();
break;
default:
printf("Wrong choice, Please enter correct choice ");
break;
}
}
}

void create()
{
front = rear = NULL;
}

void queuesize()
{
printf("\n Queue size : %d", count);
}

void enq(int data)

88
{
if (rear == NULL)
{
rear = (struct node *)malloc(1*sizeof(struct node));
rear->ptr = NULL;
rear->info = data;
front = rear;
}
else
{
temp=(struct node *)malloc(1*sizeof(struct node));
rear->ptr = temp;
temp->info = data;
temp->ptr = NULL;

rear = temp;
}
count++;
}

void display()
{
front1 = front;

if ((front1 == NULL) && (rear == NULL))


{
printf("Queue is empty");
return;

89
}
while (front1 != rear)
{
printf("%d ", front1->info);
front1 = front1->ptr;
}
if (front1 == rear)
printf("%d", front1->info);
}

void deq()
{
front1 = front;

if (front1 == NULL)
{
printf("\n Error: Trying to display elements from empty queue");
return;
}
else
if (front1->ptr != NULL)
{
front1 = front1->ptr;
printf("\n Dequed value : %d", front->info);
free(front);
front = front1;
}
else

90
{
printf("\n Dequed value : %d", front->info);
free(front);
front = NULL;
rear = NULL;
}
count--;
}

int frontelement()
{
if ((front != NULL) && (rear != NULL))
return(front->info);
else
return 0;
}

void empty()
{
if ((front == NULL) && (rear == NULL))
printf("\n Queue empty");
else
printf("Queue not empty");
}
Output:

91
92
Experiment 16
Objective – Write a program to create a circular queue and perform various operations on it.
Program:
#include<stdio.h>
# define MAX 5
int cqueue_arr[MAX];
int front = -1;
int rear = -1;
void insert(int item)
{
if((front == 0 && rear == MAX-1) || (front == rear+1))
{
printf("Queue Overflow \n");
return;
}
if(front == -1)
{
front = 0;
rear = 0;
}
else
{
if(rear == MAX-1)
rear = 0;
else
rear = rear+1;
}
cqueue_arr[rear] = item ;

93
}
void deletion()
{
if(front == -1)
{
printf("Queue Underflow\n");
return ;
}
printf("Element deleted from queue is : %d\n",cqueue_arr[front]);
if(front == rear)
{
front = -1;
rear=-1;
}
else
{
if(front == MAX-1)
front = 0;
else
front = front+1;
}
}
void display()
{
int front_pos = front,rear_pos = rear;
if(front == -1)
{
printf("Queue is empty\n");

94
return;
}
printf("Queue elements :\n");
if( front_pos <= rear_pos )
while(front_pos <= rear_pos)
{
printf("%d ",cqueue_arr[front_pos]);
front_pos++;
}
else
{
while(front_pos <= MAX-1)
{
printf("%d ",cqueue_arr[front_pos]);
front_pos++;
}
front_pos = 0;
while(front_pos <= rear_pos)
{
printf("%d ",cqueue_arr[front_pos]);
front_pos++;
}
}
printf("\n");
}
void display_menu(){
printf("1.Insert\n");
printf("2.Delete\n");

95
printf("3.Display\n");
printf("4.Display menu\n");
printf("5.Quit\n");
}
int main()
{
int choice,item;
display_menu();
do
{
printf("Enter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1 :
printf("Input the element for insertion in queue : ");
scanf("%d", &item);
insert(item);
break;
case 2 :
deletion();
break;
case 3:
display();
break;
case 4:
display_menu();
break;

96
case 5:
break;
default:
printf("Wrong choice\n");
}
}while(choice!=5);
return 0;
}
Output:

97
Experiment 17
Objective – Write a program to create a binary search tree and perform various operations on it.
Program:
#include <stdio.h>
#include <stdlib.h>

struct node
{
int key;
struct node *left, *right;
};

struct node *newNode(int item)


{
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}

void inorder(struct node *root)


{
if (root != NULL)
{
inorder(root->left);
printf("%d \n", root->key);
inorder(root->right);
}

98
}
void preorder(struct node *root)
{
if (root != NULL)
{
printf("%d \n", root->key);
preorder(root->left);
preorder(root->right);
}
}

void postorder(struct node *root)


{
if (root != NULL)
{
postorder(root->left);
postorder(root->right);
printf("%d \n", root->key);
}
}

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

99
return node;
}

struct node * minValueNode(struct node* node)


{
struct node* current = node;
while (current && current->left != NULL)
current = current->left;

return current;
}

struct node* deleteNode(struct node* root, int key)


{
if (root == NULL) return root;
if (key < root->key)
root->left = deleteNode(root->left, key);
else if (key > root->key)
root->right = deleteNode(root->right, key);
else
{
if (root->left == NULL)
{
struct node *temp = root->right;
free(root);
return temp;
}
else if (root->right == NULL)

100
{
struct node *temp = root->left;
free(root);
return temp;
}
struct node* temp = minValueNode(root->right);
root->key = temp->key;
root->right = deleteNode(root->right, temp->key);
}
return root;
}

void print_menu(){
printf("Menu:\n");
printf("Enter 1 to insert a node\nEnter 2 to display\nEnter 3
for preorder traversal\nEnter 4 for inorder traversal\nEnter 5 for postorder traveral\n");
printf("Enter 6 to delete a node\nEnter 7 to display
menu\nEnter 9 to exit\n");
}

int main()
{
int val,choice;
struct node *root = NULL;
printf("Enter the data of root node: ");
scanf("%d",&val);
root = insert(root, val);
print_menu();
do{

101
printf("Enter your choice: ");
scanf("%d",&choice);
if(choice == 1){
printf("Enter the data you want to insert: ");
int num;
scanf("%d",&num);
insert(root,num);
}
else if(choice == 2)
inorder(root);
else if(choice == 3)
preorder(root);
else if(choice == 4)
inorder(root);
else if(choice == 5)
postorder(root);
else if(choice == 6){
int num;
printf("Enter the value of node you want to delete:
");
scanf("%d",&num);
deleteNode(root,num);
}
else if(choice == 7)
print_menu();
}while(choice != 9);

return 0;
}
102
Output:

103
Experiment 18
Objective – Write a program to perform bubble sort on an array.
Program:
#include <stdio.h>
#include <stdlib.h>

void bubble_sort(int *A, int n){


int i,j,temp;
for(i=0; i<n-1; i++){
for(j=0; j<n-i-1; j++){
if(A[j]>A[j+1]){
temp=A[j];
A[j]=A[j+1];
A[j+1]=temp;
}
}
}
}

void display(int *A, int n){


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

int main(){
int *A,n,i;

104
printf("Enter the size of the array: ");
scanf("%d",&n);
A=(int*)malloc(n*sizeof(int));
printf("Enter the array elements: ");
for(i=0; i<n; i++)
scanf("%d",&A[i]);
printf("Array before sorting : ");
display(A,n);
bubble_sort(A,n);
printf("Array after sorting : ");
display(A,n);
return 0;
}
Output

105
Experiment 19
Objective – Write a program to implement insertion sort on an array.
Program:
#include <stdio.h>
#include <stdlib.h>

void insertion_sort(int *A, int n){


int temp,i,j;
for(i=0; i<n; i++){
j=i-1;
temp=A[i];
while(j>=0 && A[j]>temp){
A[j+1]=A[j];
j--;
}
A[j+1]=temp;
}
}
void display(int *A, int n){
for(int i=0; i<n; i++)
printf("%d ",A[i]);
printf("\n");
}

int main(){
int *A,n,i;
printf("Enter the size of the array: ");
scanf("%d",&n);

106
A=(int*)malloc(n*sizeof(int));
printf("Enter the array elements: ");
for(i=0; i<n; i++)
scanf("%d",&A[i]);
printf("Array before sorting : ");
display(A,n);
insertion_sort(A,n);
printf("Array after sorting : ");
display(A,n);
return 0;
}
Output

107
Experiment 20
Objective – Write a program to implement selection sort on an array.
Program:
#include <stdio.h>
#include <stdlib.h>

void selection_sort(int *A, int n){


int i,j,k,temp;
for(i=0; i<n-1; i++){
for(j=k=i; j<n; j++){
if(A[j]<A[k])
k=j;
}
temp=A[i];
A[i]=A[k];
A[k]=temp;
}
}

void display(int *A, int n){


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

int main(){
int *A,n,i;
printf("Enter the size of the array: ");

108
scanf("%d",&n);
A=(int*)malloc(n*sizeof(int));
printf("Enter the array elements: ");
for(i=0; i<n; i++)
scanf("%d",&A[i]);
printf("Array before sorting : ");
display(A,n);
selection_sort(A,n);
printf("Array after sorting : ");
display(A,n);
return 0;
}
Output:

109
Experiment 21
Objective – Write a program to perform to heap sort on an array.
Program:
#include <stdio.h>

void swap(int *a, int *b) {


int temp = *a;
*a = *b;
*b = temp;
}

void heapify(int arr[], int n, int i) {


int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;

if (left < n && arr[left] > arr[largest])


largest = left;

if (right < n && arr[right] > arr[largest])


largest = right;

if (largest != i) {
swap(&arr[i], &arr[largest]);
heapify(arr, n, largest);
}
}

110
void heapSort(int arr[], int n) {

for (int i = n / 2 - 1; i >= 0; i--)


heapify(arr, n, i);

for (int i = n - 1; i >= 0; i--) {


swap(&arr[0], &arr[i]);

heapify(arr, i, 0);
}
}

void printArray(int arr[], int n) {


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

int main() {
int arr[] = {1, 12, 9, 5, 6, 10};
int n = sizeof(arr) / sizeof(arr[0]);

heapSort(arr, n);

printf("Sorted array is \n");


printArray(arr, n);
}
Output:

111
112
Experiment 22
Objective – Write a program to perform merge sort on array.
Program
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

void merge(int *A, int l, int mid, int h){


int i,j,k;
int B[h+1];
i=l;
j=mid+1;
k=l;
while(i<=mid && j<=h){
if(A[i]<A[j])
B[k++]=A[i++];
else
B[k++]=A[j++];
}
for(;i<=mid; i++) B[k++]=A[i];
for(;j<=h; j++) B[k++]=A[j];
for(i=l; i<=h; i++) A[i]=B[i];
}

void Rmergesort(int *A, int l, int h){


if(l<h){
int mid=(l+h)/2;
Rmergesort(A,l,mid);

113
Rmergesort(A,mid+1,h);
merge(A,l,mid,h);
}
}

int main(){
int *A,n,i;
printf("Enter the number of elements: ");
scanf("%d",&n);
A=(int*)malloc(sizeof(int)*n);
printf("Enter Array elements: ");
for(i=0; i<n; i++){
scanf("%d",&A[i]);
}
Rmergesort(A,0,n-1);
printf("Array after sorting : ");
for(i=0; i<n; i++){
printf("%d ",A[i]);
}
getch();
return 0;
}
Output

114
115
Experiment 23
Objective – Write a program to perform quick sort on an array.
Program:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

int partition(int *A, int l, int h){


int pivot=A[l];
int i=l,j=h,temp;
do{
do{
i++;
}while(A[i]<=pivot);
do{
j--;
}while(A[j]>pivot);
if(i<j){
temp=A[j];
A[j]=A[i];
A[i]=temp;
}
}while(i<j);
temp=A[l];
A[l]=A[j];
A[j]=temp;
return j;
}

116
void Quicksort(int *A, int l, int h){
int j;
if(l<h){
j=partition(A,l,h);
Quicksort(A,l,j);
Quicksort(A,j+1,h);
}
}

int main(){
int *A,n,i;
printf("Enter the number of elements: ");
scanf("%d",&n);
A=(int*)malloc(sizeof(int)*(n+1));
A[n]=__INT32_MAX__;
printf("Enter Array elements: ");
for(i=0; i<n; i++){
scanf("%d",&A[i]);
}
Quicksort(A,0,n);
printf("Array after sorting : ");
for(i=0; i<n; i++){
printf("%d ",A[i]);
}
getch();
return 0;
}

117
Output

118
Experiment 24
Objective – Write a program to perform kruskals algorithm.
Program
#include <stdio.h>
#include <stdlib.h>
#include <climits>

#define V 5
int parent[V];

int find(int i)
{
while (parent[i] != i)
i = parent[i];
return i;
}

void union1(int i, int j)


{
int a = find(i);
int b = find(j);
parent[a] = b;
}

void kruskalMST(int cost[][V])


{
int mincost = 0;

119
for (int i = 0; i < V; i++)
parent[i] = i;

int edge_count = 0;
while (edge_count < V - 1) {
int min = INT_MAX, a = -1, b = -1;
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (find(i) != find(j) && cost[i][j] < min) {
min = cost[i][j];
a = i;
b = j;
}
}
}

union1(a, b);
printf("Edge %d:(%d, %d) cost:%d \n",
edge_count++, a, b, min);
mincost += min;
}
printf("\n Minimum cost= %d \n", mincost);
}

int main()
{

int cost[][V] = {

120
{ INT_MAX, 2, INT_MAX, 6, INT_MAX },
{ 2, INT_MAX, 3, 8, 5 },
{ INT_MAX, 3, INT_MAX, INT_MAX, 7 },
{ 6, 8, INT_MAX, INT_MAX, 9 },
{ INT_MAX, 5, 7, 9, INT_MAX },
};
kruskalMST(cost);

return 0;
}
Output

121
Experiment 25
Objective – Write a program to implement prims algorithm.
Program
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>

#define V 5

int minKey(int key[], bool mstSet[])


{
int min = INT_MAX, min_index;

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


if (mstSet[v] == false && key[v] < min)
min = key[v], min_index = v;

return min_index;
}

int printMST(int parent[], int graph[V][V])


{
int sum=0;
printf("Edge \tWeight\n");
for (int i = 1; i < V; i++){
printf("%d - %d \t%d \n", parent[i], i, graph[i][parent[i]]);
sum+=graph[i][parent[i]];

122
}
printf("Total cost: %d\n",sum);
}

void primMST(int graph[V][V])


{

int parent[V];

int key[V];

bool mstSet[V];

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


key[i] = INT_MAX, mstSet[i] = false;

key[0] = 0;
parent[0] = -1;

for (int count = 0; count < V - 1; count++) {

int u = minKey(key, mstSet);

mstSet[u] = true;

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

if (graph[u][v] && mstSet[v] == false && graph[u][v] < key[v])

123
parent[v] = u, key[v] = graph[u][v];
}

printMST(parent, graph);
}

int main()
{
int graph[V][V] = { { 0, 2, 0, 6, 0 },
{ 2, 0, 3, 8, 5 },
{ 0, 3, 0, 0, 7 },
{ 6, 8, 0, 0, 9 },
{ 0, 5, 7, 9, 0 } };
primMST(graph);
return 0;
}
Output:

124

You might also like