0% found this document useful (0 votes)
22 views50 pages

Dsa TP Lab Manual - Final

The document provides detailed programs for implementing various data structures, including List ADT using arrays and linked lists, Stack ADT using a singly linked list, and Queue ADT using a singly linked list. Each section includes the aim, algorithm, and code implementation for the respective data structure operations such as insertion, deletion, and display. The results confirm the successful demonstration of these implementations.

Uploaded by

suhaanand1998
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)
22 views50 pages

Dsa TP Lab Manual - Final

The document provides detailed programs for implementing various data structures, including List ADT using arrays and linked lists, Stack ADT using a singly linked list, and Queue ADT using a singly linked list. Each section includes the aim, algorithm, and code implementation for the respective data structure operations such as insertion, deletion, and display. The results confirm the successful demonstration of these implementations.

Uploaded by

suhaanand1998
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/ 50

MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI

1
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI

Ex.No. : 1
Date :
1. a) Write a program to implement the List ADT using arrays and linked lists.
a. List ADT using arrays
Aim:
To create a list using array and perform operations such as display, insertions and deletions.
Algorithm
1. Start
2. Define list using an array of size n.
3. First item with subscript or position = 0
4. Display menu on list operation
5. Accept user choice
6. If choice = 1 then
7. Locate node after which insertion is to be done
8. Create an empty location in array after the node by moving the existing elements one position ahead.
9. Insert the new element at appropriate position
10. Else if choice = 2
11. Get element to be deleted.
12. Locate the position of the element replace the element with the element in the following position.
13. Repeat the step for successive elements until end of the array.
14. Else
15. Traverse the list from position or subscript 0 to n.
16. Stop

Program
#include<stdio.h>
#include<conio.h>
#define MAX 10
void create( );
void insert( );
void deletion( );
void search( );
void display ();
int a,b[20], n, p, e, f, i, pos;
void main( )
{
int ch;
char g='y';
do
{
printf("\n Main Menu");
printf("\n 1.Create \n 2.Delete \n 3.Search \n 4.Insert \n 5.Display\n 6.Exit \n");
printf("\n Enter your Choice:");
scanf("%d", &ch);
switch(ch)
{
2
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI
case 1:
create();
break;
case 2:
deletion();
break;
case 3:
search();
break;
case 4:
insert();
break;
case 5:
display();
break;
case 6:
exit();
break;
default:
printf("\n Enter the correct choice:");
}
printf("\n Do u want to continue:");
scanf("\n%c", &g);
}
while(g=='y'||g=='Y');
getch();
}
void create( )
{
printf("\n Enter the number of nodes:");
scanf("%d", &n);
for(i=0;i<n;i++)
{ printf("\n Enter the Element:",i+1);
scanf("%d", &b[i]); } }
void deletion( ) {
printf("\n Enter the position u want to delete:");
scanf("%d", &pos);
if(pos>=n) {
printf("\n Invalid Location:");
}
else {
for(i=pos+1;i<n;i++) {
b[i-1]=b[i];
}n--; }
printf("\n The Elements after deletion:");
for(i=0;i<n;i++) {
printf("\t%d", b[i]);
}}
void search() {
printf("\n Enter the Element to be searched:");
scanf("%d", &e);
for(i=0;i<n;i++) {
3
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI
if(b[i]==e) {
printf("Value is in the %d Position", i); }
else {
printf("Value %d is not in the list:", e);
continue; }}}
void insert() {
printf("\n Enter the position u need to insert:");
scanf("%d", &pos);
if(pos>=n)
{ printf("\n invalid Location:");
}
else
{ for(i=MAX-1;i>=pos-1;i--)
{ b[i+1]=b[i];}
printf("\n Enter the element to insert:");
scanf("%d",&p);
b[pos]=p;
n++; }
printf("\n The list after insertion:");
display(); }
void display()
{
printf("\n The Elements of The list ADT are:");
for(i=0;i<n;i++)
{ printf("\n\n%d", b[i]); } }
Output

4
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI
Result: Thus the array implementation of list was demonstrated.
1. b) Write a program to implement the List ADT using linked lists.
b. List ADT using Linked List
Aim:
To create a list using Linked List and perform operations such as display, insertions and deletions.
Algorithm
1. Start
2. Define single linked list node as self referential structure
3. Create Head node with label = -1 and next = NULL using
4. Display menu on list operation
5. Accept user choice
6. If choice = 1 then
7. Locate node after which insertion is to be done
8. Create a new node and get data part
9. Insert the new node at appropriate position by manipulating address
10. Else if choice = 2
11. Get node's data to be deleted.
12. Locate the node and delink the node
13. Rearrange the links
14. Else
15. Traverse the list from Head node to node which points to null
16. Stop

Program
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
/*declaring a structure to create a node*/
struct node
{
int data;
struct node *next;
};
struct node *start;
/* inserting nodes into the list*/
/*function to insert values from beginning of the the single linked
list*/ void insertbeg(void)
{
struct node *nn;
int a;
/*allocating implicit memory to the node*/
nn=(struct node *)malloc(sizeof(struct node));
printf("enter data:");
scanf("%d",&nn->data);
a=nn->data;
if(start==NULL)
/*checking if List is empty*/ {
nn
5
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI
->next=NULL;
start=nn;
}
else {
nn
->next=start;
start=nn;
}
printf("%d succ. inserted\n",a);
return;
}
/*function to insert values from the end of the linked list*/
void insertend(void) {
struct node *nn,*lp;
int b;
nn=(struct node *)malloc(sizeof(struct node));
printf("enter data:");
scanf("%d",&nn->data);
b=nn->data;
if(start==NULL) {
nn->next=NULL;
start=nn;
}
else {
lp=start;
while(lp
->next!=NULL)
{
lp=lp->next;
}
lp->next=nn;
nn->next=NULL;
}
printf("%d is succ. inserted\n",b);
return;
}
/*function to insert values from the middle of the linked list*/
void insertmid(void) {
struct node *nn,*temp,*ptemp;
int x,v;
nn=(struct node *)malloc(sizeof(struct node));
if(start==NULL) {
printf("sll is empty\n");
return;
}
printf("enter data before which no. is to be inserted:\n");
scanf("%d",&x);
if(x==start
->data)
{
insertbeg();
return;
6
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI
}
ptemp=start;
temp=start
->next;
while(temp!=NULL&&temp
->data!=x)
{
ptemp=temp;
temp=temp
->next;
}
if(temp==NULL) {
printf("%d data does not exist\n",x);
}
else {
printf("enter data:");
scanf("%d",&nn
->data);
v=nn
->data;
ptemp
->next=nn;
nn
->next=temp;
printf("%d succ. inserted\n",v);
}
return;
}
void deletion(void) {
struct node *pt,*t;
int x;
if(start==NULL) {
printf("sll is empty\n");
return;
}
printf("enter data to be deleted:");

scanf("%d",&x);
if(x==start->data)
{
t=start;
/* assigning first node pointer to next node pointer to delete a
data from the starting of the node*/
start=start->next;
free(t);
printf("%d is succ. deleted\n",x);
return;
}
pt=start;
t=start->next;
while(t!=NULL&&t->data!=x)
{
7
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI
pt=t;t=t->next;
}
if(t==NULL)
{
printf("%d does not exist\n",x);
return;
}
else
{
pt->next=t->next;
}
printf("%d is succ. deleted\n",x);
free(t);
return;
}
void display(void)
{
struct node *temp;
if(start==NULL)
{
printf("sll is empty\n");
return;
}
printf("elements are:\n");
temp=start;
while(temp!=NULL)
{
printf("%d\n",temp->data);
temp=temp->next;
}
return;
}
/* main program*/
int main( )
{
int c,a;
start=NULL;
do
{
printf("1:insert\n2:delete\n3:display\n4:exit\nenter choice:");
scanf("%d",&c);
switch(c)
{
case 1:
printf("1:insertbeg\n2:insert end\n3:insert mid\nenter choice:");
scanf("%d",&a);
switch(a)
{
case 1:insertbeg(); break;
case 2:insertend(); break;
case 3:insertmid(); break;
} break;
8
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI
case 2:deletion(); break;
case 3:display(); break;
case 4:printf("program ends\n");break;
default:printf("wrong choice\n"); break;
}
}while(c!=4);
return 0;
}

Output

Result:

Thus the linked list implementation of list was demonstrated.

9
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI
Ex.No. : 2
Date :
2. a) Write a programs to implement Stack ADT using a singly linked list
a. Stack ADT using a singly linked list
Aim
To implement stack operations using linked list
Algorithm
1. Start
2. Define a singly linked list node for stack
3. Create Head node
4. Display a menu listing stack operations
5. Accept choice
6. If choice = 1 then
7. Create a new node with data
8. Make new node point to first node
9. Make head node point to new node
10. If choice = 2 then
11. Make temp node point to first node
12. Make head node point to next of temp node
13. Release memory
14. If choice = 3 then
15. Display stack elements starting from head node till null
16. Stop
Program
#include <stdio.h>
#include <conio.h>
#include <process.h>
#include <alloc.h>
struct node
{
int label;
struct node *next;
};
main()
{
int ch = 0;
int k;
struct node *h, *temp, *head;
head = (struct node*) malloc(sizeof(struct node));
head->next = NULL;
while(1)
{
printf("\n Stack using Linked List \n");
printf("1->Push ");
printf("2->Pop ");
printf("3->View ");
printf("4->Exit \n");
printf("Enter your choice : ");
10
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI
scanf("%d", &ch);
switch(ch)
{
case 1:
temp=(struct node *)(malloc(sizeof(struct node)));
printf("Enter label for new node : ");
scanf("%d", &temp->label);
h = head;
temp->next = h->next;
h->next = temp;
break;
case 2:
/* Delink the first node */
h = head->next;
head->next = h->next;
printf("Node %s deleted\n", h->label);
free(h);
break;
case 3:
printf("\n HEAD -> ");
h = head;
/* Loop till last node */
while(h->next != NULL)
{
h = h->next;
printf("%d -> ",h->label);
}
printf("NULL \n");
break;
case 4:
exit(0);
}
}
}
Output
Stack using Linked List
1->Push 2->Pop 3->View 4->Exit
Enter your choice : 1
Enter label for new node : 23
New node added
Stack using Linked List
1->Push 2->Pop 3->View 4->Exit
18
Enter your choice : 1
Enter label for new node : 34
Stack using Linked List
1->Push 2->Pop 3->View 4->Exit
Enter your choice : 3
HEAD -> 34 -> 23 -> NULL

Result: Thus push and pop operations of a stack was demonstrated using linked list

11
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI

2. b) Write a programs to implement Stack ADT using a singly linked list


b. Queue ADT using a singly linked list
Aim:
To implement queue operations using linked list.

Algorithm
1. Start
2. Define a singly linked list node for stack
3. Create Head node
4. Display a menu listing stack operations
5. Accept choice
6. If choice = 1 then
7. Create a new node with data
8. Make new node point to first node
9. Make head node point to new node
10. If choice = 2 then
11. Make temp node point to first node
12. Make head node point to next of temp node
13. Release memory
14. If choice = 3 then
15. Display stack elements starting from head node till null
16. Stop

Program
#include <stdio.h>
#include <conio.h>
#include <process.h>
#include <alloc.h>
struct node
{
int label;
struct node *next;
};
main()
{
int ch=0;
int k;
struct node *h, *temp, *head;
/* Head node construction */
head = (struct node*) malloc(sizeof(struct node));
head->next = NULL;
while(1)
{
printf("\n Queue using Linked List \n");
printf("1->Insert ");
printf("2->Delete ");
printf("3->View ");
printf("4->Exit\n");
printf("Enter your choice : ");

12
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI
scanf("%d", &ch);
switch(ch) {
case 1:
/* Create a new node */
temp=(struct node *)(malloc(sizeof(struct node)));
printf("Enter label for new node : ");
scanf("%d", &temp->label);/* Reorganize the links */
h = head;
while (h->next != NULL)
h = h->next;
h->next = temp;
temp->next = NULL;
break;
case 2:
/* Delink the first node */
h = head->next;
head->next = h->next;
printf("Node deleted\n");
free(h);
break;
case 3:
printf("\n\nHEAD-> ");
h=head;
while (h->next!=NULL)
{
h = h->next;
printf("%d-> ",h->label);
}
printf("NULL\n");
break;
case 4:
exit(0);
}
}
}

Output
Queue using Linked List
1->Insert 2->Delete 3->View 4->Exit
Enter your choice : 1
Enter label for new node : 12
Queue using Linked List
1->Insert 2->Delete 3->View 4->Exit
Enter your choice : 1
Enter label for new node : 23
Queue using Linked List
1->Insert 2->Delete 3->View 4->Exit
Enter your choice : 3
HEAD -> 12 -> 23 -> NULL

Result:
Thus push and pop operations of a stack was demonstrated using linked list.
13
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI
Ex.No. :3
Date :

Write a program that reads an infix expression, converts the expression to postfix form and then
evaluates the postfix expression (use stack ADT).

Infix to Postfix
Aim:
To convert infix expression to its postfix form using stack operations.

Algorithm
1. Start
2. Define a array stack of size max = 20
3. Initialize top = -1
4. Read the infix expression character-by-character
5. If character is an operand print it
6. If character is an operator
7. Compare the operator’s priority with the stack[top] operator.
8. If the stack [top] operator has higher or equal priority than the input operator,
Pop it from the stack and print it.
9. Else
10. Push the input operator onto the stack
11. If character is a left parenthesis, then push it onto the stack.
12. If the character is a right parenthesis, pop all the operators from the stack and print it
until a left parenthesis is encountered. Do not print the parenthesis.

Program

#include <stdio.h>
#include <conio.h>
#include <string.h>
#define MAX 20
int top = -1;
char stack[MAX];
char pop();
void push(char item);
int prcd(char symbol)
{
switch(symbol)
{
case '+':
case '-':
return 2;
break;
case '*':
case '/':
return 4;
break;
case '^':
case '$':
return 6;
break;
14
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI
case '(':
case ')':
case '#':
return 1;
break;
}
}
int isoperator(char symbol) {
switch(symbol) {
case '+':
case '-':
case '*':
case '/':
case '^':
case '$':
case '(':
case ')':
return 1;
break;
default:
return 0;
}
}
void convertip(char infix[],char postfix[]) {
int i,symbol,j = 0;
stack[++top] = '#';
for(i=0;i<strlen(infix);i++) {
symbol = infix[i];
if(isoperator(symbol) == 0) {
postfix[j] = symbol;
j++;
}
else {
if(symbol == '(')
push(symbol);
else if(symbol == ')') {
while(stack[top] != '(') {
postfix[j] = pop();
j++;
}
pop(); //pop out (.
}
else
{
if(prcd(symbol) > prcd(stack[top]))
push(symbol);
else
{
while(prcd(symbol) <= prcd(stack[top]))
{
postfix[j] = pop();
j++;
15
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI
}
push(symbol);
}
}
}
}
while(stack[top] != '#')
{
postfix[j] = pop();
j++;
}
postfix[j] = '\0';
}
main()
{
char infix[20],postfix[20];
clrscr();
printf("Enter the valid infix string: ");
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;
}

Output

Enter the valid infix string: a*b+c*d/e


The corresponding postfix string is: ab*cd*e/+

Result:
Thus the given infix expression was converted into postfix form using stack

16
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI
Ex.No. : 4
Date :

Write a program to implement priority queue ADT

Aim :
To Implementation Of Heap Using Priority Queues.

Algorithm
• Priority queue is a type of queue in which every element has a key associated to it and the queue
returns the element according to these keys, unlike the traditional queue which works on first come
first serve basis.

• Thus, a max-priority queue returns the element with maximum key first whereas, a min-priority
queue returns the element with the smallest key first. max-priority queue and min-priority queue

• Priority queues are used in many algorithms like Huffman Codes, Prim's algorithm, etc. It is also
used in scheduling processes for a computer, etc.

• Heaps are great for implementing a priority queue because of the largest and smallest element at the
root of the tree for a max-heap and a minheap respectively. We use a max-heap for a max-priority
queue and a min-heap for a min-priority queue.

There are mainly 4 operations we want from a priority queue:


1. Insert → To insert a new element in the queue.
2. Maximum/Minimum → To get the maximum and the minimum element from the max-priority
queue and min-priority queue respectively.
3. Extract Maximum/Minimum → To remove and return the maximum and the minimum element
from the max-priority queue and min-priority queue respectively.
4. Increase/Decrease key → To increase or decrease key of any element in the queue.

• A priority queue stores its data in a specific order according to the keys of the elements. So, inserting a
new data must go in a place according to the specified order. This is what the insert operation does.

• The entire point of the priority queue is to get the data according to the key of the data and the
Maximum/Minimum and Extract
Maximum/Minimum does this for us.

• We know that the maximum (or minimum) element of a priority queue is at the root of the max-heap (or
min-heap). So, we just need to return the element at the root of the heap.

• This is like the pop of a queue, we return the element as well as delete it from the heap. So, we have to
return and delete the root of a heap. Firstly, we store the value of the root in a variable to return it later from
the function and then we just make the root equal to the last element of the heap. Now the root is equal to the
last element of the heap, we delete the last element easily by reducing the size of the heap by 1.

• Doing this, we have disturbed the heap property of the root but we have not touched any of its children, so
they are still heaps. So, we can call Heapify on the root to make the tree a heap again.

EXTRACT-MAXIMUM(A)
max = A[1] // stroing maximum value
A[1] = A[heap_size] // making root equal to the last element
17
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI
heap_size = heap_size-1 // delete last element
MAX-HEAPIFY(A, 1) // root is not following max-heap property
return max //returning the maximum value
Program
#include <stdio.h>
int tree_array_size = 20;
int heap_size = 0;
const int INF = 100000;
void swap( int *a, int *b )
{
int t;
t = *a;
*a = *b;
*b = t;
}
//function to get right child of a node of a tree
int get_right_child(int A[], int index)
{
if((((2*index)+1) < tree_array_size) && (index >= 1))
return (2*index)+1;
return -1;
}
//function to get left child of a node of a tree
int get_left_child(int A[], int index)
{
if(((2*index) < tree_array_size) && (index >= 1))
return 2*index;
return -1;
}
//function to get the parent of a node of a tree
int get_parent(int A[], int index)
{
if ((index > 1) && (index < tree_array_size))
{
return index/2;
}
return -1;
}
void max_heapify(int A[], int index)
{
int left_child_index = get_left_child(A, index);
int right_child_index = get_right_child(A, index);
// finding largest among index, left child and right child
int largest = index;
if ((left_child_index <= heap_size) && (left_child_index>0))
{
if (A[left_child_index] > A[largest]) {
largest = left_child_index;
}
}
if ((right_child_index <= heap_size && (right_child_index>0)))
{
18
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI
if (A[right_child_index] > A[largest])
{
largest = right_child_index;
}
}
// largest is not the node, node is not a heap
if (largest != index)
{
swap(&A[index], &A[largest]);
max_heapify(A, largest);
}
}
void build_max_heap(int A[])
{
int i;
for(i=heap_size/2; i>=1; i--)
{
max_heapify(A, i);
}
}
int maximum(int A[])
{
return A[1];
}
int extract_max(int A[])
{
int maxm = A[1];
A[1] = A[heap_size];
heap_size--;
max_heapify(A, 1);
return maxm;
}
void increase_key(int A[], int index, int key)
{
A[index] = key;
while((index>1) && (A[get_parent(A, index)] < A[index]))
{
swap(&A[index], &A[get_parent(A, index)]);
index = get_parent(A, index);
}
}
void decrease_key(int A[], int index, int key)
{
A[index] = key;
max_heapify(A, index);
}
void insert(int A[], int key)
{
heap_size++;
A[heap_size] =-1*INF;
increase_key(A, heap_size, key); }
void print_heap(int A[]) {
19
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI
int i;
for(i=1; i<=heap_size; i++) {
printf("%d\n",A[i]);
} printf("\n"); }
int main() {
int A[20];
insert(A, 20);
insert(A, 15);
insert(A, 8);
insert(A, 10);
insert(A, 5);
insert(A, 7);
insert(A, 6);
insert(A, 2);
insert(A, 9);
insert(A, 1);
print_heap(A);
increase_key(A, 5, 22);
print_heap(A);
decrease_key(A, 1, 13);
print_heap(A);
printf("%d\n\n", maximum(A));
printf("%d\n\n", extract_max(A));
print_heap(A);
printf("%d\n", extract_max(A));
printf("%d\n", extract_max(A));
printf("%d\n", extract_max(A));
printf("%d\n", extract_max(A));
printf("%d\n", extract_max(A));
printf("%d\n", extract_max(A));
printf("%d\n", extract_max(A));
printf("%d\n", extract_max(A));
printf("%d\n", extract_max(A));
return 0;
}
Output

Result: Thus the implementation heap using priority queue was demonstrated.
20
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI
Ex.No. : 5
Date :
Binary Tree Operations

Write a program to perform the following operations:


a) Insert an element into a binary search tree.
b) Delete an element from a binary search tree.
c) Search for a key element in a binary search tree.

Aim:
To construct a binary search tree and perform search.

Algorithm
1. Start
2. Call insert to insert an element into binary search tree.
3. Call delete to delete an element from binary search tree.
4. Call findmax to find the element with maximum value in binary search tree
5. Call findmin to find the element with minimum value in binary search tree
6. Call find to check the presence of the element in the binary search tree
7. Call display to display the elements of the binary search tree
8. Call makeempty to delete the entire tree.
9. Stop
Insert function
1. Get the element to be inserted.
2. Find the position in the tree where the element to be inserted by checking
the elements in the tree by traversing from the root.
3. If the element to be inserted is less than the element in the current node in
the tree then traverse left subtree
4. If the element to be inserted is greater than the element in the current node
in the tree then traverse right subtree
5. Insert the element if there is no further move

Delete function
1. Get the element to be deleted.
2. Find the node in the tree that contain the element.
3. Delete the node an rearrange the left and right siblings if any present for the
deleted node

Findmax function
1. Traverse the tree from the root.
2. Find the rightmost leaf node of the entire tree and return it
3. If the tree is empty return null.

Findmin function
1. Traverse the tree from the root.
2. Find the leftmost leaf node of the entire tree and return it
3. If the tree is empty return null.
Find function
1. Traverse the tree from the root.
2. Check whether the element to searched matches with element of the current node. If match occurs return it.
3. Otherwise if the element is less than that of the element of the current node then search the leaf subtree
4. Else search right subtree. Make empty function. Make the root of the tree to point to null.
21
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI
Program
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
struct searchtree
{
int element;
struct searchtree *left,*right;
}*root;
typedef struct searchtree *node;
typedef int ElementType;
node insert(ElementType, node);
node delete(ElementType, node);
void makeempty();
node findmin(node);
node findmax(node);
node find(ElementType, node);
void display(node, int);
void main()
{
int ch;
ElementType a;
node temp;
makeempty();
while(1)
{
printf("\n1. Insert\n2. Delete\n3. Find\n4. Find min\n5. Find max\n6.Display\n7.Exit\nEnter Your Choice : ");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("Enter an element : ");
scanf("%d", &a);
root = insert(a, root);
break;
case 2:
printf("\nEnter the element to delete : ");
scanf("%d",&a);
root = delete(a, root);
break;
case 3:
printf("\nEnter the element to search : ");
scanf("%d",&a);
temp = find(a, root);
if (temp != NULL)
printf("Element found");
else
printf("Element not found");
break;
case 4:
temp = findmin(root);
if(temp==NULL)
22
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI
printf("\nEmpty tree");
else
printf("\nMinimum element : %d", temp->element);
break;
case 5:
temp = findmax(root);
if(temp==NULL)
printf("\nEmpty tree");
else
printf("\nMaximum element : %d", temp->element);
break;
case 6:
if(root==NULL)printf("\nEmpty tree");
else
display(root, 1);
break;
case 7:
clrscr();
exit(0);
default:
printf("Invalid Choice");
}}}
node insert(ElementType x,node t)
{
if(t==NULL)
{
t = (node)malloc(sizeof(node));
t->element = x;
t->left = t->right = NULL;
}
else
{
if(x < t->element)
t->left = insert(x, t->left);
else
if(x > t->element)t->right = insert(x, t->right);
}
return t;
}
node delete(ElementType x,node t)
{
node temp;
if(t == NULL)
printf("\nElement not found");
else {
if(x < t->element)
t->left = delete(x, t->left);
else if(x > t->element)
t->right = delete(x, t->right);
else {
if(t->left && t->right)
{
23
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI
temp = findmin(t->right);
t->element = temp->element;
t->right = delete(t->element,t->right);
}
else if(t->left == NULL)
{
temp = t;
t=t->right;
free (temp); }
else {
temp = t;
t=t->left;
free (temp);
}
}}
return t;
}
void makeempty() {
root = NULL;
}
node findmin(node temp) {
if(temp == NULL || temp
->left == NULL)
return temp;
return findmin(temp
->left);
}
node findmax(node temp) {
if(temp==NULL || temp
->right==NULL)
return temp;
return findmax(temp
->right);
}
node find(ElementType x, node t) {
if(t==NULL)
return NULL;
if(x<t
->element)
return find(x,t
->left);
if(x>t
->element)
return find(x,t
->right);
return t; }
void display(node t,int level) {
int i;
if(t) {
display(t
->right, level+1);
printf("\n");
24
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI
for(i=0;i<level;i++)
printf(" ");
printf("%d", t
->element);
display(t
->left, level+1);
}
}
Output:

1. Insert
2. Delete
3. Find
4. Find Min
5. Find Max
6. Display
7. Exit
Enter your Choice : 1
Enter an element : 10
1. Insert
2. Delete
3. Find
4. Find Min
5. Find Max
6. Display
7. Exit
Enter your Choice : 1
39
Enter an element : 20
1. Insert
2. Delete
3. Find
4. Find Min
5. Find Max
6. Display
7. Exit
Enter your Choice : 1
Enter an element : 5
1. Insert
2. Delete
3. Find
4. Find Min
5. Find Max
6. Display
7. Exit
Enter your Choice : 4
The smallest Number is 5
1. Insert
2. Delete
3. Find
4. Find Min
5. Find Max
25
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI
6. Display
7. Exit
Enter your Choice : 3
Enter an element : 100
Element not Found
1. Insert
2. Delete
3. Find
4. Find Min
5. Find Max
6. Display
7. Exit
Enter your Choice : 2
Enter an element : 20
1. Insert
2. Delete
3. Find
4. Find Min
5. Find Max
6. Display
7. Exit
40
Enter your Choice : 6
20
10
1. Insert
2. Delete
3. Find
4. Find Min
5. Find Max
6. Display
7. Exit
Enter your Choice : 7

Result:

The program for binary search tree is executed and verified.

26
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI
Ex.No. : 6
Date :
AVL Tree Operations

Write a program to perform the following operations


a) Insertion into an AVL-tree
b) Deletion from an AVL-tree

Aim:
To implement AVL Trees.

Algorithm

A binary search tree x is called an AVL tree, if:


1. b(x.key) ∈ {−1, 0, 1}, and
2. x.leftChild and x.rightChild are both AVL trees. = the height balance of every node
must be -1, 0, or 1insert/delete via standard algorithms

• after insert/delete: load balance b(node) might be changed to +2 or −2 for certain nodes
• re-balance load after each step

Insert operation may cause balance factor to become 2 or –2 for some node
› only nodes on the path from insertion point to root node have possibly changed in height
› So after the Insert, go back up to the root node by node, updating heights
› If a new balance factor (the difference hleft – hright ) is 2 or –2, adjust tree by rotation
around the node
Let the node that needs rebalancing be α.
There are 4 cases:
Outside Cases (require single rotation) :
1. Insertion into left subtree of left child of α.
2. Insertion into right subtree of right child of α.
Inside Cases (require double rotation) :
3. Insertion into right subtree of left child of α.
4. Insertion into left subtree of right child of α.
The rebalancing is performed through four separate rotation algorithms.
You can either keep the height or just the difference in height, i.e. the balance factor; this
has to be modified on the path of insertion even if you don‟t perform rotations
Once you have performed a rotation (single or double) you won‟t need to go back up the
tree

SINGLE ROTATION
RotateFromRight(n : reference node pointer)
{
p : node pointer;
p := n.right;
n.right := p.left;
p.left := n;
n := p
}
You also need to modify the heights or balance factors of n and p

27
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI

DOUBLE ROTATION
DoubleRotateFromRight(n : reference node pointer)
{
RotateFromLeft(n.right);
RotateFromRight(n);
}

INSERTION IN AVL TREES


Insert(T : tree pointer, x : element) :
{
if T = null then
T := new tree; T.data := x; height := 0;
case
T.data = x : return ; //Duplicate do nothing
T.data > x : return Insert(T.left, x);
if ((height(T.left)- height(T.right)) = 2){
if (T.left.data > x ) then //outside case
T = RotatefromLeft (T);
else //inside case
T = DoubleRotatefromLeft (T);}
T.data < x : return Insert(T.right, x);
code similar to the left case
Endcase
T.height := max(height(T.left),height(T.right)) +1;
return;
}

DELETION
Similar but more complex than insertion
› Rotations and double rotations needed to rebalance
› Imbalance may propagate upward so that many rotations may be needed.

Program
/*
* AVL Tree Program in C
*/

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

// structure of the tree node


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

// global initialization of root node


struct node* root = NULL;
28
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI

// function prototyping
struct node* create(int);
struct node* insert(struct node*, int);
struct node* delete(struct node*, int);
struct node* search(struct node*, int);
struct node* rotate_left(struct node*);
struct node* rotate_right(struct node*);
int balance_factor(struct node*);
int height(struct node*);
void inorder(struct node*);
void preorder(struct node*);
void postorder(struct node*);

int main()
{
int user_choice, data;
char user_continue = 'y';
struct node* result = NULL;

while (user_continue == 'y' || user_continue == 'Y')


{
printf("\n\n------- AVL TREE --------\n");
printf("\n1. Insert");
printf("\n2. Delete");
printf("\n3. Search");
printf("\n4. Inorder");
printf("\n5. Preorder");
printf("\n6. Postorder");
printf("\n7. EXIT");

printf("\n\nEnter Your Choice: ");


scanf("%d", &user_choice);

switch(user_choice)
{
case 1:
printf("\nEnter data: ");
scanf("%d", &data);
root = insert(root, data);
break;

case 2:
printf("\nEnter data: ");
scanf("%d", &data);
root = delete(root, data);
break;

case 3:
printf("\nEnter data: ");
scanf("%d", &data);
result = search(root, data);
29
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI
if (result == NULL)
{
printf("\nNode not found!");
}
else
{
printf("\n Node found");
}
break;
case 4:
inorder(root);
break;

case 5:
preorder(root);
break;

case 6:
postorder(root);
break;

case 7:
printf("\n\tProgram Terminated\n");
return 1;

default:
printf("\n\tInvalid Choice\n");
}

printf("\n\nDo you want to continue? ");


scanf(" %c", &user_continue);
}

return 0;
}

// creates a new tree node


struct node* create(int data)
{
struct node* new_node = (struct node*) malloc (sizeof(struct node));

// if a memory error has occurred


if (new_node == NULL)
{
printf("\nMemory can't be allocated\n");
return NULL;
}
new_node->data = data;
new_node->left = NULL;
new_node->right = NULL;
return new_node;
}
30
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI

// rotates to the left


struct node* rotate_left(struct node* root)
{
struct node* right_child = root->right;
root->right = right_child->left;
right_child->left = root;

// update the heights of the nodes


root->ht = height(root);
right_child->ht = height(right_child);

// return the new node after rotation


return right_child;
}

// rotates to the right


struct node* rotate_right(struct node* root)
{
struct node* left_child = root->left;
root->left = left_child->right;
left_child->right = root;

// update the heights of the nodes


root->ht = height(root);
left_child->ht = height(left_child);

// return the new node after rotation


return left_child;
}

// calculates the balance factor of a node


int balance_factor(struct node* root)
{
int lh, rh;
if (root == NULL)
return 0;
if (root->left == NULL)
lh = 0;
else
lh = 1 + root->left->ht;
if (root->right == NULL)
rh = 0;
else
rh = 1 + root->right->ht;
return lh - rh;
}

// calculate the height of the node


int height(struct node* root)
{
int lh, rh;
31
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI
if (root == NULL)
{
return 0;
}
if (root->left == NULL)
lh = 0;
else
lh = 1 + root->left->ht;
if (root->right == NULL)
rh = 0;
else
rh = 1 + root->right->ht;

if (lh > rh)


return (lh);
return (rh);
}

// inserts a new node in the AVL tree


struct node* insert(struct node* root, int data)
{
if (root == NULL)
{
struct node* new_node = create(data);
if (new_node == NULL)
{
return NULL;
}
root = new_node;
}
else if (data > root->data)
{
// insert the new node to the right
root->right = insert(root->right, data);

// tree is unbalanced, then rotate it


if (balance_factor(root) == -2)
{
if (data > root->right->data)
{
root = rotate_left(root);
}
else
{
root->right = rotate_right(root->right);
root = rotate_left(root);
}
}
}
else
{
// insert the new node to the left
32
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI
root->left = insert(root->left, data);

// tree is unbalanced, then rotate it


if (balance_factor(root) == 2)
{
if (data < root->left->data)
{
root = rotate_right(root);
}
else
{
root->left = rotate_left(root->left);
root = rotate_right(root);
}
}
}
// update the heights of the nodes
root->ht = height(root);
return root;
}

// deletes a node from the AVL tree


struct node * delete(struct node *root, int x)
{
struct node * temp = NULL;

if (root == NULL)
{
return NULL;
}

if (x > root->data)
{
root->right = delete(root->right, x);
if (balance_factor(root) == 2)
{
if (balance_factor(root->left) >= 0)
{
root = rotate_right(root);
}
else
{
root->left = rotate_left(root->left);
root = rotate_right(root);
}
}
}
else if (x < root->data)
{
root->left = delete(root->left, x);
if (balance_factor(root) == -2)
{
33
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI
if (balance_factor(root->right) <= 0)
{
root = rotate_left(root);
}
else
{
root->right = rotate_right(root->right);
root = rotate_left(root);
}
}
}
else
{
if (root->right != NULL)
{
temp = root->right;
while (temp->left != NULL)
temp = temp->left;

root->data = temp->data;
root->right = delete(root->right, temp->data);
if (balance_factor(root) == 2)
{
if (balance_factor(root->left) >= 0)
{
root = rotate_right(root);
}
else
{
root->left = rotate_left(root->left);
root = rotate_right(root);
}
}
}
else
{
return (root->left);
}
}
root->ht = height(root);
return (root);
}

// search a node in the AVL tree


struct node* search(struct node* root, int key)
{
if (root == NULL)
{
return NULL;
}

if(root->data == key)
34
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI
{
return root;
}

if(key > root->data)


{
search(root->right, key);
}
else
{
search(root->left, key);
}
}

// inorder traversal of the tree


void inorder(struct node* root)
{
if (root == NULL)
{
return;
}

inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}

// preorder traversal of the tree


void preorder(struct node* root)
{
if (root == NULL)
{
return;
}

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


preorder(root->left);
preorder(root->right);
}

// postorder traversal of the tree


void postorder(struct node* root)
{
if (root == NULL)
{
return;
}

postorder(root->left);
postorder(root->right);
printf("%d ", root->data);
}
35
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI

Output

36
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI
Ex.No. : 7
Date :
Write a programs for the implementation of BFS and DFS for a given graph
7. a) BREADTH FIRST TRAVERSAL
Aim: To implement breadth first graph traversal.
Algorithm
BFS (G, s) //Where G is the graph and s is the source node let Q be queue.
Q.enqueue( s ) //Inserting s in queue until all its neighbour vertices are marked.
mark s as visited.
while ( Q is not empty)
//Removing that vertex from queue, whose neighbour will be visited now
v = Q.dequeue( )
//processing all the neighbours of v
for all neighbours w of v in Graph G
if w is not visited
Q.enqueue( w ) //Stores w in Q to further visit its neighbour
mark w as visited.
Program
#include <stdio.h>
int n, i, j, visited[10], queue[10], front = -1, rear = -1;
int adj[10][10];
void bfs(int v)
{ for (i = 1; i <= n; i++)
if (adj[v][i] && !visited[i])
queue[++rear] = i;
if (front <= rear)
{ visited[queue[front]] = 1;
bfs(queue[front++]); } }
void main()
{ int v;
printf("Enter the number of vertices: ");
scanf("%d", &n);
for (i = 1; i <= n; i++)
{ queue[i] = 0;
visited[i] = 0; }
printf("Enter graph data in matrix form: \n");
for (i = 1; i <= n; i++)
for (j = 1; j <= n; j++)
scanf("%d", &adj[i][j]);
printf("Enter the starting vertex: ");
scanf("%d", &v);
bfs(v);
printf("The node which are reachable are: \n");
for (i = 1; i <= n; i++)
if (visited[i])
printf("%d\t", i);
else
printf("BFS is not possible. Not all nodes are reachable");
return 0; }

37
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI
Output :

Result :
Thus the graph using breadth first search traversal was demonstrated

38
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI
7. b) DEPTH FIRST TRAVERSAL
Aim:
To implement depth first graph traversal.
Algorithm
DFS-iterative (G, s): //Where G is graph and s is source vertex
let S be stack
S.push( s ) //Inserting s in stack
mark s as visited.
while ( S is not empty):
//Pop a vertex from stack to visit next
v = S.top( )
S.pop( )
//Push all the neighbours of v in stack that are not visited
for all neighbours w of v in Graph G:
if w is not visited :
S.push( w )
mark w as visited
DFS-recursive(G, s):
mark s as visited
for all neighbours w of s in Graph G:
if w is not visited:
DFS-recursive(G, w)
Program
#include<stdio.h>
void DFS(int);
int G[10][10],visited[10],n; //n is no of vertices and graph is sorted in array G[10][10]
void main()
{
int i,j;
printf("Enter number of vertices:");

scanf("%d",&n);
//read the adjecency matrix
printf("\nEnter adjecency matrix of the graph:");

for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
//visited is initialized to zero
for(i=0;i<n;i++)
visited[i]=0;
DFS(0);
}
void DFS(int i)
{
int j;
printf("\n%d",i);
visited[i]=1;
for(j=0;j<n;j++)

39
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI
if(!visited[j]&&G[i][j]==1)
DFS(j);
}

Output

Result :
Thus the graph using depth first search traversal was demonstrated.

40
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI
Ex.No. : 8
Date :
Write a programs for implementing the following searching methods
a) Linear search b) Binary search.
Linear Search
Aim
To perform linear search of an element on the given array.
Algorithm
1. Start
2. Read number of array elements n
3. Read array elements Ai, i = 0,1,2,…n–1
4. Read search value
5. Assign 0 to found
6. Check each array element against search
7. If Ai = search then
found = 1
Print "Element found"
Print position i
Stop
8. If found = 0 then
print "Element not found"
Stop
Program
#include <stdio.h>
#include <conio.h>
main()
{
int a[50],i, n, val, found;
clrscr();
printf("Enter number of elements : ");
scanf("%d", &n);
printf("Enter Array Elements : \n");
for(i=0; i<n; i++)
scanf("%d", &a[i]);
printf("Enter element to locate : ");
scanf("%d", &val);
found = 0;
for(i=0; i<n; i++)
{
if (a[i] == val)
{
printf("Element found at position %d", i);
found = 1;
break; } }
if (found == 0)
printf("\n Element not found");
getch(); }

41
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI

Output
Enter number of elements : 7
Enter Array Elements :
23 6 12 5 0 32 10
Enter element to locate : 5
Element found at position 3
Result
Thus an array was linearly searched for an element's existence.

42
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI
Binary Search
Aim
To locate an element in a sorted array using Binary search method
Algorithm
1. Start
2. Read number of array elements, say n
3. Create an array arr consisting n sorted elements
4. Get element, say key to be located
5. Assign 0 to lower and n to upper
6. While (lower < upper)
a. Determine middle element mid = (upper+lower)/2
b. If key = arr[mid] then
i. Print mid
ii. Stop
c. Else if key > arr[mid] then
i. lower = mid + 1
d. else
i. upper = mid – 1
7. Print "Element not found"
8. Stop
Program
#include <stdio.h>
void main()
{
int a[50],i, n, upper, lower, mid, val, found, att=0;
printf("Enter array size : ");
scanf("%d", &n);
for(i=0; i<n; i++)
a[i] = 2 * i;
printf("\n Elements in Sorted Order \n");
for(i=0; i<n; i++)
printf("%4d", a[i]);
printf("\n Enter element to locate : ");
scanf("%d", &val);
upper = n;
lower = 0;
found = -1;
while (lower <= upper)
{
mid = (upper + lower)/2;
att++;
if (a[mid] == val)
{
printf("Found at index %d in %d attempts", mid, att);
found = 1;
break;
}
else if(a[mid] > val)
upper = mid - 1;
else
lower = mid + 1;

43
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI
}
if (found == -1)
printf("Element not found");
}

Output
Enter array size : 10
Elements in Sorted Order
0 2 4 6 8 10 12 14 16 18
Enter element to locate : 16
Found at index 8 in 2 attempts

Result
Thus an element is located quickly using binary search method.

44
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI
Ex.No. : 9
Date :
Write a programs for implementing the following sorting methods:
a) Bubble sort b) Selection sort c) Insertion sort d) Radix sort.
9. a) Bubble sort
Aim: To sort an array of N numbers using Bubble sort.
Algorithm
1. Start
2. Read number of array elements n
3. Read array elements Ai
4. Outer Index i varies from last element to first element
a. Index j varies from first element to i-1
i. Compare elements Aj and Aj+1
ii. If out-of-order then swap the elements
iii. Display array elements after each pass
iv. Display the final sorted list
5. Stop
Program
#include <stdio.h>
main()
{
int n, t, i, j, k, a[20], p=0;
printf("Enter total numbers of elements: ");
scanf("%d", &n);
printf("Enter %d elements: ", n);
for(i=0; i<n; i++)
scanf("%d", &a[i]);
for(i=n-1; i>=0; i--)
{ for(j=0; j<i; j++)
{ if(a[j] > a[j+1])
{ t = a[j];
a[j] = a[j+1];
a[j+1] = t; } } p++;
printf("\n After Pass %d : ", p);
for(k=0; k<n; k++)
printf("%d ", a[k]); }
printf("\n Sorted List : ");
for(i=0; i<n; i++)
printf("%d ", a[i]); }

Output
Enter total numbers of elements: 8
Enter 8 elements: 8 6 10 3 1 2 5 4
After Pass 1 : 6 8 3 1 2 5 4 10
After Pass 2 : 6 3 1 2 5 4 8 10
After Pass 3 : 3 1 2 5 4 6 8 10
After Pass 4 : 1 2 3 4 5 6 8 10
After Pass 5 : 1 2 3 4 5 6 8 10
After Pass 6 : 1 2 3 4 5 6 8 10
After Pass 7 : 1 2 3 4 5 6 8 10
Sorted List : 1 2 3 4 5 6 8 10
Result: Thus an array was sorted using bubble sort.
45
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI
9. b) Selection sort
Aim:
To sort an array of N numbers using Selection sort.
Algorithm

Step 1: Repeat Steps 2 and 3 for i = 0 to n-1


Step 2: CALL SMALLEST(arr, i, n, pos)
Step 3: SWAP arr[i] with arr[pos]
[END OF LOOP]
Step 4: EXIT

SMALLEST (arr, i, n, pos)


Step 1: [INITIALIZE] SET SMALL = arr[i]
Step 2: [INITIALIZE] SET pos = i
Step 3: Repeat for j = i+1 to n
if (SMALL > arr[j])
SET SMALL = arr[j]
SET pos = j
[END OF if]
[END OF LOOP]
Step 4: RETURN pos
Program
#include <stdio.h>
int main() {
int arr[10]={6,12,0,18,11,99,55,45,34,2};
int n=10;
int i, j, position, swap;
clrscr();
for (i = 0; i < (n - 1); i++) {
position = i;
for (j = i + 1; j < n; j++) {
if (arr[position] > arr[j])
position = j;
}
if (position != i) {
swap = arr[i];
arr[i] = arr[position];
arr[position] = swap;
}
}
printf("\n\t sorted array \n");
for (i = 0; i < n; i++) {
printf("%d\t", arr[i]); }
return 0;
}
Output
Sorted Array

0 2 6 11 12 18 34 45 55 99
Result
Thus array elements was sorted using selection sort.
46
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI

9. c) Insertion sort
Aim:
To sort an array of N numbers using Insertion sort.
Algorithm
1. Start
2. Read number of array elements n
3. Read array elements Ai
4. Outer index i varies from second element to last element
5. Inner index j is used to compare elements to left of outer index
6. Insert the element into the appropriate position.
7. Display the array elements after each pass
8. Display the sorted array elements.
9. Stop
Program
void main()
{
int i, j, k, n, temp, a[20], p=0;
printf("Enter total elements: ");
scanf("%d",&n);
printf("Enter array elements: ");
for(i=0; i<n; i++)
scanf("%d", &a[i]);
for(i=1; i<n; i++)
{
temp = a[i];
j = i - 1;
while((temp<a[j]) && (j>=0))
{
a[j+1] = a[j];
j = j - 1;
}
a[j+1] = temp;
p++;
printf("\n After Pass %d: ", p);
for(k=0; k<n; k++)
printf(" %d", a[k]);
}
printf("\n Sorted List : ");
for(i=0; i<n; i++)
printf(" %d", a[i]);
}

47
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI
Output
Enter total elements: 6

Enter array elements: 34 8 64 51 32 21


After Pass 1: 8 34 64 51 32 21
After Pass 2: 8 34 64 51 32 21
After Pass 3: 8 34 51 64 32 21
After Pass 4: 8 32 34 51 64 21
After Pass 5: 8 21 32 34 51 64
Sorted List : 8 21 32 34 51 64

Result:
Thus array elements was sorted using insertion sort.

48
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI
9. d) Radix sort
Aim:
To sort an array of N numbers using Radix sort.

Algorithm
1. Radix_Sort(Array, p) // p is the number of passes
2. for j = 1 to p do
3. int count_array[10] = {0};
4. for i = 0 to n do
count_array[key of(Array[i]) in pass j]++ // count array stores the count of key
5. for k = 1 to 10 do
count_array[k] = count_array[k] + count_array[k-1]
6. for i = n-1 downto 0 do
result_array[ count_array[key of(Array[i])] ] = Array[j]
//Construct the resulting array (result_array) by checking
//new Array[i] position from count_array[k]
count_array[key of(Array[i])]--
7. for i=0 to n do
Array[i] = result_array[i]
//The main array Array[] now contains sorted numbers based on the current digit position.
8. the end for(j)
9. end function

Program

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int Max_value(int Array[], int n) // This function gives maximum value in array[]
{
int i;
int maximum = Array[0];
for (i = 1; i < n; i++){
if (Array[i] > maximum)
maximum = Array[i];
}
return maximum;
}
void radixSortalgorithm(int Array[], int n) // Main Radix Sort sort function
{
int i,digitPlace = 1;
int result_array[20]; // resulting array
int largest = Max_value(Array, n); // Find the largest number to know number of digits
while(largest/digitPlace >0){
int count_array[10] = {0};
for (i = 0; i < n; i++) //Store the count of "keys" or digits in count[]
count_array[ (Array[i]/digitPlace)%10 ]++;
for (i = 1; i < 10; i++)
count_array[i] += count_array[i - 1];
for (i = n - 1; i >= 0; i--) // Build the resulting array
{
result_array[count_array[ (Array[i]/digitPlace)%10 ] - 1] = Array[i];
49
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab
MARUTHAM NELLI GROUP OF INSTITUTUIONS – JAYAM ARTS AND SCIENCE COLLEGE, DHARMAPURI
count_array[ (Array[i]/digitPlace)%10 ]--;
}
for (i = 0; i < n; i++) // numbers according to current digit place
Array[i] = result_array[i];
digitPlace *= 10; // Move to next digit place
}
}
void displayArray(int Array[], int n) // Function to print an array
{
int i;
for (i = 0; i < n; i++)
printf("%d ", Array[i]);
printf("\n");
}
int main()
{
int array1[] = {20,30,40,90,60,100,50,70};
int n = sizeof(array1)/sizeof(array1[0]);
clrscr();
printf("Unsorted Array is : ");
displayArray(array1, n);
radixSortalgorithm(array1, n);
printf("Sorted Array is: ");
displayArray(array1, n);
return 0;
}
Output

Result:

Thus array elements was sorted using Radix sort.

50
T. Prakash, Asst. Prof., Department of Computer Science.
Data Structure and Algorithms Lab

You might also like