0% found this document useful (0 votes)
68 views64 pages

DS Programs

The document outlines a series of programming experiments focused on data structures, including searching algorithms, sorting methods, linked lists, queues, and binary trees. Each experiment includes a brief description and sample code for implementation in C. The document serves as a practical guide for learning and applying fundamental data structure concepts.
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)
68 views64 pages

DS Programs

The document outlines a series of programming experiments focused on data structures, including searching algorithms, sorting methods, linked lists, queues, and binary trees. Each experiment includes a brief description and sample code for implementation in C. The document serves as a practical guide for learning and applying fundamental data structure concepts.
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/ 64

Data Structures Programs

SL NO NAME OF THE EXPERIMENTS

1.Wri t Write a program to search for an element in an array using binary and linear search.
2.
Write a program to sort list of n numbers using Bubble Sort algorithm
3. Perform the Insertion and Selection Sort on the input {75,8,1,16,48,3,7,0} and display
the output in descending order
4. Write a program to insert the elements {61,16,8,27} into singly linked list and delete
8,61,27 from the list. Display your list after each insertion and deletion
5.
Wr Write a program to insert the elements {61,16,8,27} into linear queue and delete
three elements from the list. Display your list after each insertion and deletion.
6. Write a program to simulate the working of Circular queue using the array.

7. Write a program to insert the elements {61,16,8,27} into ordered singly linked list and
delete 8,61,27 from the list. Display your list after each insertion and deletion
8.
Wr Write a Program for Tower of Honoiu problem using recursion.
9.
Writ Write a recursive program to find GCD of 3 Numbers.

10.
Wr Write a program to demonstrate working of stack using linked list.
11. Write a Program to convert an infix expression x^y/(5*z)+2 to its postfix expression.

12.
Wr Write a program to evaluate a postfix expression 53+82-*
13. Write a program to create a binary tree with the elements {18,15,40,50,30,17,41} .After
Creation insert 45 and 19 into tree and delete 15 ,17 and 41 from tree. Display the tree
on each insertion and deletion operation.
14. Write a program to create binary search tree with the elements{2,5,1,3,9,0,6} and
perform inorder , preorder and post order traversal.
15. Write a program to Sort the following elements using heap sort {9,16,32,8,4,1,5,8,0}.

16. Given S1={“Flowers”}; S2={“are beautiful”}; I.Find the length of S1 . II. Concatenate
S1 and S2 . III. Extract the substring “low” from S1. IV. Find “are ” in S2 and replace it
with “is”.
17. Write a Program to implement adjacency matrix of a graph.

18. Write a program to insert/retrieve an entry into hash from a hash table with open
addressing using linear probing .

PROGRAM 1:
WRITE A PROGRAM TO SEARCH FOR AN ELEMENT IN AN ARRAY USING BINARY
AND LINEAR SEARCH.
#include <stdio.h>

// Function for Linear Search


int linearSearch(int arr[], int length, int target) {
int i;
for (i = 0; i <length; i++) {
if (arr[i] == target) {
return i; // Return the index if found
}
}
return -1; // Return -1 if not found
}

// Function for Binary Search


int binarySearch(int arr[], int length, int target) {
int low = 0;
int high = length - 1;

while (low <= high) {


int mid = low + (high - low) / 2; // Calculate mid index

if (arr[mid] == target) {
return mid; // Return the index if found
} else if (arr[mid] < target) {
low = mid + 1; // Search in the right half
} else {
high = mid - 1; // Search in the left half
}
}
return -1; // Return -1 if not found
}
int main() {
int search_list[] = {3, 1, 9, 8, 7, 12, 56, 23, 89};
int length = sizeof(search_list) / sizeof(search_list[0]);
int target,i,j;
int linearResult, binaryResult;
// Linear Search
printf("Enter a value to search using Linear Search: ");
scanf("%d", &target);

linearResult = linearSearch(search_list, length, target);

if (linearResult != -1) {
printf("Linear Search: Element found at index %d\n", linearResult);
} else {
printf("Linear Search: Element not found\n");
}
// Sorting the array for Binary Search
// Here we use a simple bubble sort for demonstration purposes
for ( i = 0; i < length - 1; i++) {
for ( j = 0; j < length - i - 1; j++) {
if (search_list[j] > search_list[j + 1]) {
int temp = search_list[j];
search_list[j] = search_list[j + 1];
search_list[j + 1] = temp;
}
}
}
printf("Sorted Array for Binary Search: ");
for ( i = 0; i < length; i++) {
printf("%d ", search_list[i]);
}
printf("\n");

// Binary Search
printf("Enter a value to search using Binary Search: ");
scanf("%d", &target);

binaryResult = binarySearch(search_list, length, target);

if (binaryResult != -1) {
printf("Binary Search: Element found at index %d\n", binaryResult);
} else {
printf("Binary Search: Element not found\n");
}

return 0;
}

Output:

PROGRAM 2:
WRITE A PROGRAM TO SORT LIST OF N NUMBERS USING BUBBLE SORT
ALGORITHM.

#include <stdio.h>
// Function to perform Bubble Sort
void bubbleSort(int arr[], int n) {
// Outer loop for each pass
int i,j;
for ( i = 0; i < n - 1; i++) {
// Inner loop for comparing adjacent elements
for ( j = 0; j < n - i - 1; j++) {
// Swap if the element found is greater than the next element
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

// Function to print the array


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

int main() {
int n,i;
int arr[100];

// Input number of elements


printf("Enter the number of elements: ");
scanf("%d", &n);

// Input elements of the array


printf("Enter %d numbers:\n", n);
for ( i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

// Display original array


printf("Original array: ");
printArray(arr, n);

// Perform Bubble Sort


bubbleSort(arr, n);

// Display sorted array


printf("Sorted array: ");
printArray(arr, n);

return 0;
}
Output:
PROGRAM 3: PERFORM THE INSERTION AND SELECTION SORT ON THE INPUT
{75,8,1,16,48,3,7,0} AND DISPLAY THE OUTPUT IN DESCENDING ORDER.

#include <stdio.h>

// Function to perform Insertion Sort


void insertionSort(int arr[], int n) {
int i,j,key;
for ( i = 1; i < n; i++) {
key = arr[i];
j = i - 1;

// Move elements of arr[0..i-1], that are less than key,


// to one position ahead of their current position
while (j >= 0 && arr[j] < key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}

// Function to perform Selection Sort


void selectionSort(int arr[], int n) {
int i,j,maxIndex,temp;
for ( i = 0; i < n - 1; i++) {
// Find the maximum element in the unsorted array
maxIndex = i;
for ( j = i + 1; j < n; j++) {
if (arr[j] > arr[maxIndex]) {
maxIndex = j;
}
}
// Swap the found maximum element with the first element
temp = arr[maxIndex];
arr[maxIndex] = arr[i];
arr[i] = temp;
}
}

// Function to print the array


void printArray(int arr[], int n) {
int i;
for ( i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int arr[] = {75, 8, 1, 16, 48, 3, 7, 0};
int arr2[] = {75, 8, 1, 16, 48, 3, 7, 0};

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

printf("Original array: ");


printArray(arr, n);

// Perform Insertion Sort


insertionSort(arr, n);
printf("Sorted array using Insertion Sort in descending order: ");
printArray(arr, n);

// Resetting the array for Selection Sort

// Perform Selection Sort


selectionSort(arr2, n);
printf("Sorted array using Selection Sort in descending order: ");
printArray(arr2, n);

return 0;
}
Output:

Program 4: Program to insert the elements {61,16,8,27} into singly linked list and delete
8,61,27 from the list . Display your list after each insertion and deletion.

#include <stdio.h>
#include <malloc.h> //calloc: static & malloc: dynamic
#include <stdlib.h>
struct node {
int value;
struct node *next;
};
void insert();
void display();
void delete();
int count();
typedef struct node DATA_NODE;//renaming struct with new name
DATA_NODE *head_node, *first_node, *temp_node = 0, *prev_node, next_node;
int data;
int main()
{
int option = 0;
printf("Singly Linked List Example - All Operations\n");
while (1) //true in all ca
{
printf("\nOptions\n");
printf("1 : Insert into Linked List \n");
printf("2 : Delete from Linked List \n");
printf("3 : Display Linked List\n");
printf("Others : Exit()\n"); // printf(“case 4: exit()\n”);
printf("Enter your option:");
scanf("%d", &option);
switch (option)
{
case 1:
insert();
display(); break;
case 2:
delete(); display(); break;
case 3:
display(); break;
case 4: default:
exit(0);
}
}
return 0;
}
void insert()
{
printf("\nEnter Element for Insert Linked List : \n");
scanf("%d", &data);
temp_node = (DATA_NODE *) malloc(sizeof (DATA_NODE));
temp_node->value = data;
if (first_node == 0) //first node= header node
{
first_node = temp_node;
}
else {
head_node->next = temp_node;
}
temp_node->next = 0;
head_node = temp_node;
fflush(stdin);
}
void delete()
{
int countvalue, pos, i = 0;
countvalue = count();
temp_node = first_node;
printf("\nEnter Position for Delete Element : \n");
scanf("%d", &pos); //input pos=2;
if (pos> 0 &&pos<= countvalue) //(if (2>0 && 2<=4) true)
{
if (pos == 1)// (2==1) false//exit goto else
{
temp_node = temp_node -> next;
first_node = temp_node;
printf("\nDeleted Successfully \n\n");
}
else
{
while (temp_node != 0)
{
if (i == (pos - 1)) //0==2-1false(0==1)
{
prev_node->next = temp_node->next;
if(i == (countvalue - 1))//0==4-1->0==3
{
head_node = prev_node;
}
printf("\nDeleted Successfully \n\n");
break;
}
Else
{
i++;//i=1
prev_node = temp_node;
temp_node = temp_node -> next;
}
}
}
}
else
printf("\nInvalid Position \n\n");
}
void display()
{
int count = 0;
temp_node = first_node;
printf("\nDisplay Linked List : \n");
while (temp_node != 0)
{

printf(" %d\t ", temp_node->value);


count++;
temp_node = temp_node -> next;
}
printf("\nNo Of Items In Linked List : %d\n", count);
}
int count()
{
int count = 0;
temp_node = first_node;
while (temp_node != 0)
{
count++;
temp_node = temp_node -> next;
}
printf("\nNo Of Items In Linked List : %d\n", count);
return count;
}
Program 5:
Write a program to insert the elements {61,16,8,27} into linear queue and delete three
elements from the list. Display your list after each insertion and deletion.

#include <stdio.h>
#define MAX 20
#include<stdlib.h>
int queue_array[MAX];
int rear = - 1;
int front = - 1;
void insert()
{
int add_item;
if (rear == MAX - 1)
printf("Queue Overflow \n");
else
{
if (front == - 1)
/*If queue is initially empty */
front = 0;
printf("\nEnter element : ");
scanf("%d", &add_item);
printf("\n%d is inserted in queue\n",add_item);
printf("------------------------------\n");
rear = rear + 1;
queue_array[rear] = add_item;
}
}
void delete()
{
if (front == - 1 || front > rear)
{
printf("Queue Underflow \n");
return ;
}
else
{
printf("\nElement deleted from queue is : %d\n", queue_array[front]);
printf("------------------------------\n");
front = front + 1;
}
}
void display()
{
int i;
if (front == - 1)
printf("Queue is empty \n");
else
{
printf("\nQueue is : ");
for (i = front; i <= rear; i++)
printf("%d ", queue_array[i]);
printf("\n------------------------------");
printf("\n");
}
}
int main()
{
printf("Perform operations on queue\n");
printf("------------------------------\n");
printf("\tMenu");
printf("\n------------------------------\n");
printf("1. Insert element \n");
printf("2. Delete element \n");
printf("3. Display queue\n");
printf("4. Exit\n");
printf("------------------------------\n");
int ch;
while (1)
{
printf("Choose operation : ");
scanf("%d", &ch);
switch(ch)
{
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
display();
break;
case 4:
exit(1);
default:
printf("Invalid operation \n");
}
}
return 0;
}
Program 6:
Write a program to simulate the working of Circular queue using the array.

#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* next;
};
struct node *f = NULL;
struct node *r = NULL;
void enqueue(int d) //Insert elements in Queue
{
struct node* n;
n = (struct node*)malloc(sizeof(struct node));
n->data = d;
n->next = NULL;
if((r==NULL)&&(f==NULL))
{
f = r = n;
r->next = f;
}
else
{
r->next = n;
r = n;
n->next = f;
}
}
void dequeue() // Delete an element from Queue
{
struct node* t;
t = f;
if((f==NULL)&&(r==NULL))
printf("\nQueue is Empty");
else if(f == r){
f = r = NULL;
free(t);
}
else{
f = f->next;
r->next = f;
free(t);

}
}
void print(){ // Print the elements of Queue
struct node* t;
t = f;
if((f==NULL)&&(r==NULL))
printf("\nQueue is Empty");
else{
do{
printf("\n%d",t->data);
t = t->next;
}while(t != f);
}
}
int main()
{
int opt,n,i,data;
printf("Enter Your Choice:-");
do{
printf("\n\n 1 for Insert the Data in Queue\n 2 for show the Data in Queue \n 3 for Delete
the data from the Queue\n 0 for Exit\n");
scanf("%d",&opt);
switch(opt){
case 1:
printf("\nEnter the size of data");
scanf("%d",&n);
printf("\nEnter your data");
i=0;
while(i<n){
scanf("%d",&data);
enqueue(data);
i++;
}
break;
case 2:
print();
break;
case 3:
dequeue();
break;
case 0:
break;
default:
printf("\nIncorrect Choice");

}
}while(opt!=0);
return 0;
}
Program 7:
Write a program to insert the elements {61,16,8,27} into ordered singly linked list and delete
8,61,27 from the list. Display your list after each insertion and deletion

#include <stdio.h>

#include <stdlib.h>

// Create a node

struct Node {

int data;

struct Node* next;

};
// Insertion operation

void insert(struct Node** head_ref, int new_data) {

// Allocate memory to a node

struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));

// insert the data

new_node->data = new_data;

new_node->next = (*head_ref);

// Move head to new node

(*head_ref) = new_node;

// Delete a node

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

return;

// Find the key to be deleted

while (temp != NULL && temp->data != key) {


prev = temp;
temp = temp->next;

// If the key is not present

if (temp == NULL) return;


// Remove the node

prev->next = temp->next;

free(temp);

// Sort the linked list

void sortLinkedList(struct Node** head_ref)

struct Node *current = *head_ref, *index = NULL;

int temp;

if (head_ref == NULL) {

return;

} else {

while (current != NULL) {


// index points to the node next to current

index = current->next;

while (index != NULL) {

if (current->data > index->data) {

temp = current->data;

current->data = index->data;

index->data = temp;

index = index->next;

current = current->next;
}

}
}

// Print the linked list

void printList(struct Node* node) {

while (node != NULL) {


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

node = node->next;

// Driver program

int main() {

struct Node* head = NULL;

insert(&head, 27);

insert(&head, 8);

insert(&head, 16);

insert(&head, 61);

printf("Linked list: ");


printList(head);

sortLinkedList(&head);

printf("\nSorted List: ");

printList(head);

printf("\nAfter deleting an element: ");

deleteNode(&head, 8);

deleteNode(&head, 61);

deleteNode(&head, 27);

printList(head);
}
Program 8:

Write a Program for Tower of Honoiu problem using recursion

#include <stdio.h>
void toh(int , char, char ,char);

int count = 0;

void main(){
char source = 's', temp = 'T', dest = 'D';

int n;

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

scanf("%d" , &n);

printf("\n Sequence is :");

toh(n, source , temp , dest);

printf("\n The Number of Moves: %d" , count);

void toh(int n , char source ,char temp , char dest)

if(n > 0){

toh(n-1 , source , dest , temp);

printf("\n Move Disk %d %c -> %c \n" , n , source , dest);


count++;

toh(n-1 , temp , source , dest);

}
Program 9:

Write a recursive program to find GCD of 3 Numbers.

# include <stdio.h>

int GCD(int m , int n){

if(n==0)

{
return m;

else if(n>m)

return(GCD(n,m));

else

return(GCD(n , m %n));

void main(){

int k , n,m;

printf("Enter Three Numbers:\n");


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

printf("\n GCD(%d %d %d) = %d\n", k,m,n , GCD(k,GCD(m,n)));

}
Program 10:

Write a program to demonstrate working of stack using linked list.

#include <stdio.h>
#include<stdlib.h>

#include<conio.h>

#include<malloc.h>

struct stack

int info;

struct stack *link;

};

struct stack *TOP = NULL;

//functions

//push function
void push(int item)

struct stack *NEWNODE;

NEWNODE = (struct stack *) malloc(sizeof(struct stack));

NEWNODE -> info = item;

if(TOP == NULL)

NEWNODE -> link = NULL;

TOP = NEWNODE;

else
{

NEWNODE -> link = TOP;


TOP = NEWNODE;

//pop function

int pop(){

struct stack *TEMP;

int ITEM;

if(TOP == NULL)

printf("stack underflow\n");

return -1;

TEMP = TOP;

ITEM = TEMP -> info;


TOP = TOP -> link;

free(TEMP);

return ITEM;

//display function

void display()

struct stack * CURRPTR = TOP;

if(CURRPTR == NULL)
{

printf("stack is empty\n");

return;

}
printf("stack elements are:\n");

while(CURRPTR != NULL)

printf("%d\n" , CURRPTR -> info);

CURRPTR = CURRPTR -> link;

void main()

int item , choice;

do
{

printf("\n *MainMenu*");

printf("\n 1.PUSH");

printf("\n 2. POP*");

printf("\n 3. DISPLAY");

printf("\n 4. EXIT");

printf("\n ENTER YOUR OPTION:");

scanf("%d", &choice);

switch(choice)

{
case 1: printf("\n Enter the number to be pushed on stack");

scanf("%d", &item);
push(item);

break;

case 2: item = pop();


if(item!=-1){

printf("\n popped item is : %d", item);

break;

case 3: display();

break;

while(choice!=4);

}
Program 11:
Write a Program to convert an infix expression x^y/(5*z)+2 to its postfix expression.

#include<stdio.h>
#include<conio.h>
#include<string.h>
#define MAX 20

char stack[MAX]; int top=0;


char pop();
void push(char); int prcd(char);
int isoperator(char);
void convertip(char [],char []);

void main()
{
char infix[20],postfix[20];

printf("Enter the valid infix string:\n"); gets(infix);


convertip(infix,postfix);
printf("The corresponding postfix string is: "); puts(postfix);
getch();
}
void push(char item)
{
top++; stack[top]=item;
}
char pop()
{
char a; a=stack[top]; top--;
return a;
}
void convertip(char infix[],char postfix[])
{
int i,symbol,j=0; stack[++top]='#'; for(i=0;i<strlen(infix);i++)
{
symbol=infix[i]; if(symbol=='(') push(symbol);
else if(symbol==')')
{
while(stack[top]!='(')
{
postfix[j]=pop(); j++;
}
pop();//pop out (.
}
else if (isoperator(symbol)==1)
{
while(stack[top] != '#' && prcd(symbol)<=prcd(stack[top]))
{
postfix[j]=pop(); j++;
}
push(symbol);
}//end of else.
else if(isoperator(symbol)==0)
{
postfix[j]=symbol; j++;
}
}//end of for. while(stack[top]!='#')
{
postfix[j]=pop(); j++;
}
postfix[j]='\0';//null terminate string.
}
int prcd(char symbol)
{
if(symbol == '^' || symbol == '$') return 6;
else if(symbol == '*' || symbol == '/') return 4;
else if(symbol == '+' || symbol == '-') return 2;
else if(symbol == '(' || symbol == ')' || symbol == '#') return 1;
else return 0;
}
int isoperator(char symbol)
{

if(symbol == '^' || symbol == '$' || symbol == '+' || symbol == '-' || symbol == '*' || symbol == '/' ||
symbol == '(' || symbol == ')')
return 1;

else return 0;
}

Program 12:
Write a program to evaluate a postfix expression 53+82-*
#include<stdio.h>
int stack[20];
int top = -1;
void push(int x)
{
stack[++top] = x;
}
int pop()
{
return stack[top--];
}
int main()
{
char exp[20];
char *e;
int n1,n2,n3,num;
printf("Enter the expression : ");
scanf("%s",exp);
e = exp;
while(*e != '\0')
{
if(*e)
{
num = *e - 48;
push(num);
}
else
{
n1 = pop();
n2 = pop();
switch(*e)
{
case '+':
{
n3 = n1 + n2;
break;
}
case '-':
{
n3 = n2 - n1;
break;
}
case '*':
{
n3 = n1 * n2;
break;
}
case '/':
{
n3 = n2 / n1;
break;
}
}
push(n3);
}
e++;
}
printf("\nThe result of expression %s is : %d\n",exp,pop());
return 0;
}
Prograam 13:
Write a program to create a binary tree with the elements {18,15,40,50,30,17,41} .After Creation
insert 45 and 19 into tree and delete 15 ,17 and 41 from tree. Display the tree on each
insertion and deletion operation.

#include<stdio.h>
#include<stdlib.h>

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

typedef struct node NODE;


NODE *root = NULL;

/*display function */
void disp(struct node *ptr, int level)
{
int i;
if(ptr!=NULL)
{
disp(ptr->right ,level+1);
for(i=0;i<level;i++)
printf(" ");
printf("%2d\n", ptr->info);
disp(ptr->left,level+1);

}
}

/*Create function */
void create(int item){

NODE *newnode, *currptr , *ptr;


newnode = (NODE *) malloc(sizeof(NODE));
newnode->info = item;
newnode->left = NULL;
newnode->right = NULL;
if(root == NULL)
root=newnode;
else
{
currptr = root;
while(currptr !=NULL)
{
ptr = currptr;
currptr = (item> currptr -> info)? currptr -> right : currptr ->left;
}
if(item < ptr->info)
ptr-> left = newnode;
else
ptr->right = newnode;
}

/* inorder successor in BST will be the minimum key in right subtree*/


NODE *getInSuccessor(NODE * ptr){
while(ptr->left !=NULL){
ptr=ptr->left;
}
return ptr;
}
NODE *deletion(NODE *p, int item){
NODE *temp;
if(!p)
{
printf("Unable to delete . No such key exists.\n");
return p;
}
else if(item>p->info)
p->right = deletion(p-> right , item);
else if(item < p->info )
p->left = deletion(p-> left, item);
else
{
if(p->left ==NULL){
temp = p->right;
free(p);
return temp;
}
else if(p->right == NULL){
temp = p->left;
free(p);
return temp;
}
temp = getInSuccessor(p->right);
p->info = temp->info;
p->right = deletion(p->right ,temp->info);
}
return p;
}

void main()
{
int item,ch,n,i;
while(1)
{
printf("\n Binary Search Tree Menu");
printf("\n ---------------------------\n");
printf("\n 1.Insert");
printf("\n 2. Delete");
printf("\n 3.Display");
printf("\n4. Exit");
printf("\n Enter the choice:");
scanf("%d", &ch);
switch(ch)
{
case 1: printf("\n enter the number of nodes:");
scanf("%d" , &n);
for(i=0;i<n;i++){
printf("\n enter the data for the node :");
scanf("%d", &item);
create(item);
}
break;
case 2: printf("\n Enter an Item to be deleted:");
scanf("%d" , &item);
root = deletion(root,item);
disp(root,1);
break;
case 3:printf("\n The Binary Tree nodes are:\n\n\n\n");
disp(root, 1);
break;
case 4 : exit(1);
}
}
}
Program 14:
Write a program to create binary search tree with the elements{2,5,1,3,9,0,6} and perform
inorder , preorder and post order traversal.

#include <stdio.h>
#include <stdlib.h>

struct node
{
int data;
struct node *left;
struct node *right;
};
int main()
{
void insert(struct node **,int);
void inorder(struct node *);
void postorder(struct node *);
void preorder(struct node *);

struct node *ptr = NULL;


int data,choice,no,i,num;
char ch;
do
{
printf("\nInsert a new node in the Binary Tree : 1");
printf("\nDisplay the Binary Tree in Preorder Traversal : 2");
printf("\nDisplay the Binary Tree in Inorder Traversal : 3");
printf("\nDisplay the Binary Tree in Postorder Traversal : 4");
printf("\nExit : 5\n");
printf("\nEnter your choice : ");
scanf("%d",&choice);
switch (choice)
{
case 1 : printf("\nEnter the value to be inserted : ");
scanf("%d",&data);
insert(&ptr,data);
break;
case 2 : printf("\nPreorder Traversal of the Binary Tree : ");
preorder(ptr);
printf("\n");
break;
case 3 : printf("\nInorder Traversal of the Binary Tree : ");
inorder(ptr);
printf("\n");
break;
case 4 : printf("\nPostorder Traversal of the Binary Tree : ");
postorder(ptr);
printf("\n");
break;
case 5 :
break;
default : printf("\nInvalid Choice\n");
}
}
while (choice !=5);
}
void insert(struct node **p, int num)
{
if((*p)==NULL)
{
(*p) = (struct node *)malloc(sizeof(struct node));
(*p)->left = NULL;
(*p)->right = NULL;
(*p)->data = num;
return;
}
else
{
if(num==(*p)->data)
{
printf("\nRepeated Entry Error, Value Rejected\n");
return;
}
if(num<(*p)->data)
{
insert(&((*p)->left),num);
}
else
{
insert(&((*p)->right),num);
}
}
return;
}
void inorder(struct node *p)
{
if(p!=NULL)
{
inorder(p->left);
printf("%d ",p->data);
inorder(p->right);
}
else
return;
}
void preorder(struct node *p)
{
if(p!=NULL)
{
printf("%d ",p->data);
preorder(p->left);
preorder(p->right);
}
else
return;
}
void postorder(struct node *p)
{
if(p!=NULL)
{
postorder(p->left);
postorder(p->right);
printf("%d ",p->data);
}
else
return;

}
Program 15: Write a program to Sort the following elements using heap sort
{9,16,32,8,4,1,5,8,0}.
#include<stdio.h>
int temp;
void heapify(int arr[], int size, int i){
int largest = i; int left = 2*i + 1;
int right = 2*i + 2;
if (left < size && arr[left] >arr[largest]) largest = left;
if (right < size && arr[right] > arr[largest]) largest = right;
if (largest != i)
{
temp = arr[i]; arr[i]= arr[largest]; arr[largest] = temp;
heapify(arr, size, largest);
}
}
void heapSort(int arr[], int size)
{
int i;
for (i = size / 2 - 1; i >= 0; i--) heapify(arr, size, i);
for (i=size-1; i>=0; i--)
{
temp = arr[0]; arr[0]= arr[i]; arr[i] = temp; heapify(arr, i, 0);
}
}
void main(){
int arr[] = {9,16,32,8,4,1,5,8,0};
int i;
int size = sizeof(arr)/sizeof(arr[0]); heapSort(arr, size);
printf("The sorted elements are : \n\n"); for (i=0; i<size; ++i);
printf("%d\n",arr[i]);
}
Program 16:
Given S1={“Flowers”}; S2={“are beautiful”}; I.Find the length of S1 . II. Concatenate S1 and S2
.
III. Extract the substring “low” from S1. IV. Find “are ” in S2 and replace it with “is”.

#include <stdio.h>

//function to find the length of an string

int stringLength(char str[])


{
int length = 0;
while(str[length]!='\0'){
length++;
}
return length;
}

//function to concatenate two strings

void StringConcat(char s1[],char s2[],char result[]){


int i = 0, j=0;
while(s1[i]!='\0'){
result[i] = s1[i];
i++;
}

while(s2[j]!='\0'){
result[i] = s2[j];
i++;
j++;
}
result[i] = '\0';
}

//Function to extract a substring


void subStringExtract(char str[], int start, int length , char result[]){
int i;
for(i=0;i<length;i++){
result[i] = str[start + i];
}
result[i] = '\0';
}

//Function to replace a word in a string


void stringReplace(char str[], char find[], char replace[], char result[]){
int i =0, j=0,k,flag=0,start = -1;
//find the position of the substring
while(str[i]!='\0'){
k=0;
}
while(str[i+k] == find[k] && find[k] != '\0'){
k++;
}
if(find[k] == '\0')
{
flag = 1;
start = i;

}
i++;

//Copy original string while replacing the word


i=0;
while(str[i]!='\0')
{
if(i == start){
for(k = 0; replace[k]!= '\0'; k++,j++){
result[j] = replace[k];
}
i += stringLength(find);
}
else{
result[j++] = str[i++];

}
}
result[j]= '\0';
}

int main()
{
char S1[] = "Flowers";
char S2[] = "are beautiful";
char concatResult[50], substringresult[10],repalceResult[50];

printf("\nLength of S1:%d\n", stringLength(S1));


StringConcat(S1,S2, concatResult);

printf("\nConcatenated String: %s\n", concatResult);


subStringExtract(S1 , 1,3,substringresult);

printf("\n:Extracted Substring:%s\n", substringresult);

stringReplace(S2, "are","is", repalceResult);


printf("\n Modified S2: %s\n", repalceResult);
}
Program 17:
Write a Program to implement adjacency matrix of a graph
#include <stdio.h>
#define MAX 10
//function to display adjacency matrix
void displayMatrix(int matrix[MAX][MAX], int vertices)
{
int i ,j;
printf("\n Adjacency matrix:\n");
for(i=0;i<vertices;i++){
for(j=0;j<vertices;j++){
printf("%d", matrix[i][j]);
}
printf("\n");
}
}

void main(){
int matrix[MAX][MAX] = {0};
int vertices , edges, i,src,dest,choice;
//get the number of vertices and edges
printf("enter the number of vertices:");
scanf("%d", &vertices);
printf("enter the number of edges");
scanf("%d", &edges);

//choose graph type


printf("enter 1 for directed graph or 2 for undirected graph:");
scanf("%d", &choice);

//input edges
for(i = 0;i<edges; i++){
printf("enter edges(source destination):");
scanf("%d %d" , &src, &dest);
matrix[src-1][dest-1] = 1;

if(choice == 2){
matrix[dest-1][src-1] = 1;

}
}
//display the adjacency matrix
displayMatrix(matrix, vertices);
}
Program 18:
Write a program to insert/retrieve an entry into hash from a hash table .with open addressing
using linear probing .
#include <stdio.h>
#include <stdlib.h>

#define TABLE_SIZE 11 // Define the hash table size

//hash table structure

int hashTable[TABLE_SIZE];

//sentinel value for empty slots


#define EMPTY -1

//HASH FUNCTION
int hashFunction(int key){
return key % TABLE_SIZE;
}
//insert function using linear probing
void insert(int key){
int index = hashFunction(key);
int originalIndex = index;

//Linear probing to find an empty slot


while(hashTable[index] != EMPTY){
index = (index + 1) % TABLE_SIZE;
if(index == originalIndex){
printf("hash table is full. cannot insert %d\n", key);
return;
}
}
hashTable[index] = key;
printf("Inserted %d at index %d\n" , key , index);
}

//Search function using linear probing


int search(int key){
int index = hashFunction(key);
int originalIndex = index;

//Linear probing to search for the key


while(hashTable[index] != EMPTY){
if(hashTable[index] == key){
return index;
}

index = (index + 1) % TABLE_SIZE;


if(index == originalIndex){
break;
}
}
return -1;
}

//Display hash table

void display(){
int i;
printf("\n Hash Table:\n");
for(i = 0; i< TABLE_SIZE;i++){
if(hashTable[i] == EMPTY)
{
printf("Index %d : EMPTY\n" , i);
}
else
{
printf("Index %d : %d\n", i , hashTable[i]);
}

}
printf("\n");
}

int main(){
int num , key , i;

// Initialize hash table with empty values


for(i = 0; i< TABLE_SIZE ; i++){
hashTable[i] = EMPTY;
}
//get the number of elements to insert
printf("Hash Table Size is : %d\n", TABLE_SIZE);
printf("Enter the number of elements to insert(<=%d):" , TABLE_SIZE);
scanf("%d, &num");

//Insert elements into the hash table


printf("enter %d elements :\n", num);
for(i=0;i<num;i++){
scanf("%d" , &key);
insert(key);
}

display();

//Search for a key


printf("enter a key to search:");
scanf("%d" , &key);

int result = search(key);


if(result != -1)
printf("key %d found at index %d\n" , key , result);

else

printf("key %d not found in the hash table\n", key);

return 0;
}

You might also like