0% found this document useful (0 votes)
6 views76 pages

Wa0000

The document outlines various data structure implementations, including stack and list operations using arrays and linked lists. It provides algorithms and code examples for push, pop, insertion, deletion, and searching operations. Additionally, it demonstrates the implementation of a queue using linked lists.

Uploaded by

narrayanan.ar
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)
6 views76 pages

Wa0000

The document outlines various data structure implementations, including stack and list operations using arrays and linked lists. It provides algorithms and code examples for push, pop, insertion, deletion, and searching operations. Additionally, it demonstrates the implementation of a queue using linked lists.

Uploaded by

narrayanan.ar
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/ 76

1

DE P A RT M E N T O F CY B E R SE C U RI T Y
2 0 C S 3 L - D A T A S T RU C T U R E S A N D A L G O R I T H M S
L A B O R A T O RY
E x no: 1a S t a ck u s i n g
A rray
Da te :

Aim
To implement stack operations using array.

A l g o r i th m
1. Start
2. Define a array stack of size max = 5
3. Initialize top = -1
4. Display a menu listing stack operations
5. Accept choice
6. If choice = 1 then
If top < max -1
Increment top
Store element at current position of top
E lse
Print Stack overflow
Else If choice = 2 then
If top < 0 then
Print Stack underflow
E lse
Display current top element
Decrement top
Else If choice = 3 then
Display stack elements starting from top
7. Stop

P ro g ram
/* Stack Operation using Arrays */
#include <stdio.h>
#include <conio.h>
#define max 5
static int stack[max];
int top = -1;
void push(int x)
{
2

stack[++top] = x;
}
int pop()
{
return (stack[top--]);
}

void view()
{
int i;
if (top < 0)
printf("\n Stack Empty \n"); else
{
printf("\n Top-->");
for(i=top; i>=0; i--)
{
printf("%4d", stack[i]);
}
printf("\n");
}
}

void main()
{
int ch=0, val;
//clrscr();

while(ch != 4)
{
printf("\n STACK OPERATION \n");
printf("1.PUSH ");
printf("2.POP ");
printf("3.VIEW ");
printf("4.QUIT \n");
printf("Enter Choice : ");
scanf("%d", &ch);
switch(ch)
{
case 1:
if(top < max-1)
{
printf("\nEnter Stack element : "); scanf("%d", &val);
push(val);
}
e l se
printf("\n Stack Overflow \n"); break;
case 2:
if(top < 0)
printf("\n Stack Underflow \n"); else
{
3

val = pop();
printf("\n Popped element is %d\n", val);
}
break;
case 3:
view(); break;
//case 4:
//exit(0);
default:
printf("\n Invalid Choice \n");
}
}
}

Ou tpu t

STACK OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 1

Enter Stack element : 12STACK

OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 1

Enter Stack element : 23

STACK OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 1

Enter Stack element : 34STACK

OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 1

Enter Stack element : 45STACK

OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 3

Top--> 45 34 23 12STACK
4

OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 2 Popped

e l e me n t i s 4 5

STACK OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 3

Top--> 34 23 12STACK

OPERATION
1. PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 4

Re s u l t
Thus push and pop operations of a stack was demonstrated using arrays.
5

E x. No . 1 b Li s t u s i n g A rray
Da te :

Aim
To perform various operations on List ADT using array implementation.

A l g o r i th m
1. Start
2. Create a list of n elements
3. Display list operations as a menu
4. Accept user choice
5. If choice = 1 then
Get position of element to be deleted
Move elements one position upwards thereon.
Decrement length of the list
Else if choice = 2
Get position of element to be inserted.
Increment length of the list
Move elements one position downwards thereonStore
the new element in corresponding position
Else if choice = 3
Traverse the list and inspect each element
Report position if it exists.
6. Stop

P ro g ram
/* List operation using Arrays */
#include <stdio.h>
#include <conio.h>

void create();
void insert();
void search();
void deletion();
void display();

int i, e, n, pos; static int b[50];

void main()
{
int ch;
char g = 'y'; create();
do
{
printf("\n List Operations");
printf("\n 1.Deletion\n 2.Insert\n 3.Search\n4.Exit\n");
printf("Enter your choice: ");
6

scanf("%d", &ch);
switch(ch)
{
case 1:
deletion();
break;
case 2:
insert();
break;
case 3:
search();
break;
case 4:
exit(0);
default:
printf("\n Enter the correct choice:");
}
printf("Do you want to continue: ");
fflush(stdin);
scanf("\n %c",&g);
} while(g=='y' || g=='Y');
getch();
}
void create()
{
printf("\n Enter the number of elements:");
scanf("%d",&n);
printf("\n Enter list elements: "); for(i=0; i<n; i++)
scanf("%d", &b[i]);
}

void deletion()
{
printf("\n enter the position you 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("List elements after deletion");
display();
}
void search()
{
int flag = 0;
printf("\n Enter the element to be searched: "); scanf("%d", &e);
for(i=0; i<n; i++)
{
if(b[i] == e)
7

{
flag = 1;
printf("Element is in the %d position", i); break;
}
}
if(flag == 0)
printf("Value %d is not in the list", e);
}

void insert()
{
printf("\n Enter the position you need to insert: "); scanf("%d", &pos);
if(pos >= n)
printf("\n Invalid location"); else
{

++n ;
for(i=n; i>pos; i--)
b[i] = b[i-1];
printf("\n Enter the element to insert: "); scanf("%d", &e);
b[pos] = e;
}
printf("\n List after insertion:"); display();
}

void display()
{
for(i=0; i<n; i++) printf("\n %d", b[i]);
}
8

Ou tpu t

Enter the number of elements:5


Enter list elements: 12 23 34 45 56

List Operations1.Deletion
2.Insert 3.Search
4.Exit
Enter your choice:2
Enter the position you need to insert: 1Enter the element to
insert: 99
List after insertion:
12
99
23
34
45
56
Do you want to continue: y

List Operations1.Deletion
2.Insert 3.Search
4. Exit
Enter your choice:1
Enter the position you want to delete: 3

Elements after deletion12


99
23
45
56
Do you want to continue: n

Re s u l t
Thus various operations was successfully executed on list using array
implementation.
9

E x. No . 2 a I m pl e m e n t a t i o n o f L i n k e d L i s t
Da te :

Aim
To define a singly linked list node and perform operations such as insertions and
deletions dynamically.

A l g o r i th m
1. Start
2. Define single linked list node as self referential structure
3. Create Head node with -1 and next = NULL using
4. Display menu on list operation
5. Accept user choice
6. If choice = 1 then
Locate node after which insertion is to be done
Create a new node and get data part
Insert new node at appropriate position by manipulating addressElse if
choice = 2
Get node's data to be deleted. Locate
the node and delink the nodeRearrange
the links
E lse
Traverse the list from Head node to node which points to null
7. Stop

P ro g r am

# i n cl u de < s t di o . h >
# i n cl u de < m a l l o c. h >
# i n cl u de < s t dl i b. h >

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

void insert();
10

void display();
void delete();
int count();

typedef struct node DATA_NODE;

DATA_NODE *head_node, *first_node, *temp_node = 0, *prev_node, next_node;


int data;

i n t m a i n () {
int option = 0;

printf("Singly Linked List Example - All Operations\n");

while (option < 5) {

printf("\nOptions\n");
printf("1 : Insert into Linked List \n");
printf("2 : Delete from Linked List \n");
printf("3 : Display Linked List\n");
printf("4 : Count Linked List\n");
printf("Others : Exit()\n");
printf("Enter your option:");
scanf("%d", &option);
switch (option) {
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
display();
11

break;
case 4:
count();
break;
default:
break;
}
}

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 = temp_node;
} el se {
head_node->next = temp_node;
}
temp_node->next = 0;
head_node = temp_node;
fflush(stdin);
}

void delete() {
int countvalue, pos, i = 0;
countvalue = count();
12

temp_node = first_node;
printf("\nDisplay Linked List : \n");

printf("\nEnter Position for Delete Element : \n");


scanf("%d", &pos);

if (pos > 0 && pos <= countvalue) {


if (pos == 1) {
temp_node = temp_node -> next;
first_node = temp_node;
printf("\nDeleted Successfully \n\n");
} el se {
while (temp_node != 0) {
if (i == (pos - 1)) {
prev_node->next = temp_node->next;
if(i == (countvalue - 1))
{
head_node = prev_node;
}
printf("\nDeleted Successfully \n\n");
break;
} el se {
i ++;
prev_node = temp_node;
temp_node = temp_node -> next;
}
}
}
} el se
printf("\nInvalid Position \n\n");
}

void display() {
13

int count = 0;
temp_node = first_node;
printf("\nDisplay Linked List : \n");
while (temp_node != 0) {
printf("# %d # ", temp_node->value);
count++;
temp_node = temp_node -> next;
}
printf("\nNo Of Items In Linked List : %d\n", count);
}

i n t c o u n t () {
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;
}

Re s u l t :

Linked list was implemented successfully.


14
E x. No . 2 b S t a ck U s i n g L i n k e d
L i s t Da t e :

Aim
To implement stack operations using linked list.

A l g o r i th m
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
Create a new node with data
Make new node point to first
node
Make head node point to new
nodeElse If choice = 2 then
Make temp node point to first node
Make head node point to next of temp
nodeRelease memory
Else If choice = 3 then
Display stack elements starting from head node till null
7. Stop

P ro g ram

/* Stack using Single Linked List */#include

<stdio.h>
#include <conio.h> #include
<process.h>#include <alloc.h>
struct node
{
int label;
struct node *next;
};

ma i n ( )
{
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)
{
15
printf("\n Stack using Linked List \n");printf("1->Push
");
printf("2->Pop ");
printf("3->View ");printf("4
->Exit \n");
printf("Enter your choice : ");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);
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);
}
}
}

Ou tpu t

Stack using Linked List


1->Push 2->Pop 3->View 4->ExitEnter
your choice : 1
Enter label for new node : 23New node
16
added

Stack using Linked List


1->Push 2->Pop 3->View 4->ExitEnter
your choice : 1
Enter label for new node : 34

Stack using Linked List


1- >Push 2->Pop 3->View 4->ExitEnter
your choice : 3
HEAD -> 34 -> 23 -> NULL

Re s u l t
Thus push and pop operations of a stack was demonstrated using linked list.

E x. No . 3 Que ue U s i n g L i n k e d
17
L i s t D a te :

Aim
To implement queue operations using linked list.

A l g o r i th m
1. Start
2. Define a singly linked list node for queue
3. Create Head node
4. Display a menu listing queue operations
5. Accept choice
6. If choice = 1 then
Create a new node with data
Make new node point to first
node
Make head node point to new
nodeElse If choice = 2 then
Make temp node point to first node
Make head node point to next of temp
nodeRelease memory
Else If choice = 3 then
Display stack elements starting from head node till null
7. Stop

P ro g ram
/* Queue using Single Linked List */#include <stdio.h>

#include <stdlib.h>

/* Structure with a node and a pointer */

struct node

int data;

struct node *next;

} *rear,*front,*temp,*newNode;

/* Initialising front and rear in empty list */

void create()

{
18
front = rear = NULL;

/* Function to insert elements in the queue */

void enqueue(int data)

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

newNode -> data = data;

newNode -> next = NULL;

if(rear != NULL)

rear -> next = newNode;

rear = newNode; // Make the new node as REAR

e l se

front = rear = newNode; // In a empty queue, the inserted element becomes FRONT and
REAR

/* Function to dequeue elements in a queue */

int dequeue()

int data;

data = front -> data;

temp = front; // Copy FRONT to a temporary node

front = front -> next; // Move FRONT to the next node

free(temp); // Delete the temporary node


19
if(front == NULL)

rear = NULL;

return data;

/* Function to check if thw queue is empty */

int empty()

if(front == NULL)

return 1;

e l se

return 0;

/* Function to display elements */

void display()

if(empty())

printf("\nEMPTY QUEUE\n");

e l se

temp = front;

printf("\nQUEUE ELEMENTS : ");

while(temp != NULL)

{
20
printf("%d ",temp -> data);

temp = temp -> next;

}}}

/* Main Function */

int main()

int num,choice;

while(1)

printf("\n\nQUEUE OPERATIONS\n\n1.ENQUEUE\n2.DEQUEUE\n3.DISPLAY\n\n");

scanf("%d",&choice);

switch (choice)

case 1:

printf("\nEnter item : ");

scanf("%d",&num);

enqueue(num);

break;

case 2:

if(!(empty()))

printf("\nDequeued element : %d",dequeue());

break;

case 3:

display();

break;

default: exit(0);
21
}}

return 0;

Ou tpu t

Queue using Linked List


1->Insert 2->Delete 3->View 4->ExitEnter
your choice : 1
Enter label for new node : 12

Queue using Linked List


1->Insert 2->Delete 3->View 4->ExitEnter
your choice : 1
Enter label for new node : 23

Queue using Linked List


1- >Insert 2->Delete 3->View 4->ExitEnter
your choice : 3
HEAD -> 12 -> 23 -> NULL

Re s u l t
Thus insert and delete operations of a queue was demonstrated using linked
list.
22

E x. No . 4 P o l y n om i al
A d di t i o n D a t e :

Aim
To add any two given polynomial using linked lists.

A l g o r i th m
1. Create a structure for polynomial with exp and coeff terms.
2. Read the coefficient and exponent of given two polynomials p and q.
3. While p and q are not null, repeat step 4.
If powers of the two terms are equal then
Insert the sum of the terms into the sum
PolynomialAdvance p and q
Else if the power of the first polynomial> power of second then
Insert the term from first polynomial into sum polynomial
Advance p
E lse
Insert the term from second polynomial into sum polynomial
Advance q
4. Copy the remaining terms from the non empty polynomial into the
sumpolynomial
5. Stop
23

P ro g ram

/* Polynomial Addition */

/* Add two polynomials */

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

struct link
{
int coeff;int
pow;
struct link *next;
};
struct link *poly1=NULL,*poly2=NULL,*poly=NULL;

void create(struct link *node)


{
char ch;do
{
printf("\nEnter coefficient: ");scanf("%d",
&node->coeff); printf("Enter exponent: ");
scanf("%d", &node->pow);
node->next = (struct link*)malloc(sizeof(struct
link));
node = node->next;
node->next = NULL;
printf("\n continue(y/n): ");fflush(stdin);
ch=getch();
} while(ch=='y' || ch=='Y');
}

void show(struct link *node)


{
while(node->next!=NULL)
{
printf("%dx^%d", node->coeff, node->pow);node=node
->next;
if(node->next!=NULL)printf(" + ");
}
}

void polyadd(struct link *poly1, struct link *poly2, struct


link *poly)
{
24

while(poly1->next && poly2->next)


{
if(poly1->pow > poly2->pow)
{
poly->pow = poly1->pow; poly
->coeff = poly1->coeff; poly1 =
poly1->next;
}
else if(poly1->pow < poly2->pow)
{
poly->pow = poly2->pow; poly
->coeff = poly2->coeff;
poly2 = poly2->next;
}
e l se
{
poly->pow = poly1->pow;
poly->coeff = poly1->coeff + poly2->coeff;poly1 =
poly1->next;
poly2 = poly2->next;
}
poly->next=(struct link *)malloc(sizeof(struct link));poly=poly->next;
poly->next=NULL;
}
while(poly1->next || poly2->next)
{
if(poly1->next)
{
poly->pow = poly1->pow; poly
->coeff = poly1->coeff;poly1 =
poly1->next;
}
if(poly2->next)
{
poly->pow = poly2->pow; poly
->coeff = poly2->coeff;poly2 =
poly2->next;
}
poly->next = (struct link *)malloc(sizeof(struct
link));
poly = poly->next;poly
->next = NULL;
}
}

ma i n ( )
{
poly1 = (struct link *)malloc(sizeof(struct link)); poly2 = (struct link
*)malloc(sizeof(struct link)); poly = (struct l i nk
*)malloc(sizeof(struct link));
25

printf("Enter 1st Polynomial:");create(poly1);


printf("\nEnter 2nd Polynomial:");
create(poly2);
printf("\nPoly1: ");show(poly1);
printf("\nPoly2: ");show(poly2);
polyadd(poly1, poly2, poly);
printf("\nAdded Polynomial: ");
show(poly);
}

Ou tpu t

Enter 1st Polynomial:


Enter coefficient: 5
Enter exponent: 2
continue(y/n): y
Enter coefficient: 4
Enter exponent: 1
continue(y/n): y
Enter coefficient: 2
Enter exponent: 0
continue(y/n): n

Enter 2nd Polynomial:


Enter coefficient: 5
Enter exponent: 1
continue(y/n): y
Enter coefficient: 5
Enter exponent: 0
continue(y/n): n

Poly1: 5x^2 + 4x^1 + 2x^0Poly2:


5x^1 + 5x^0
Added Polynomial: 5x^2 + 9x^1 + 7x^0

Re s u l t
Thus the two given polynomials were added using lists.

E x. No . 5 I n fi x T o P o s tf i x
C o n ve r s i o n D a t e :
26

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

A l g o r i th m
1. Start
2. Define a array stack of size max = 20
3. Initialize top = -1
4. Read the infix expression character-by-
characterIf character is an operand
print it
If character is an operator
Compare the operator’s priority with the stack[top] operator.
If the stack [top] has higher/equal priority than the input operator,
Pop it from the stack and print it.
E lse
Push the input operator onto the
stack
If character is a left parenthesis, then push it onto the stack.
If character is a right parenthesis, pop all operators from stack and
printit until a left parenthesis is encountered. Do not print the
parenthesis.
If character = $ then Pop out all operators, Print them and Stop

P ro g r am:

I n fi x T o P o s t fi x C o n ve r s i o n

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

/* Variable declarations */
char infix_string[20], postfix_string[20];
int top;
int stack[20];

int pop();
int precedence(char symbol);
int isEmpty();
void infix_to_postfix();
int check_space(char symbol);
void push(long int symbol);

int main()
{
int count, length;
char temp;
top = -1;
27
printf("\nINPUT THE INFIX EXPRESSION : ");
scanf("%s", infix_string);
infix_to_postfix();
printf("\nEQUIVALENT POSTFIX EXPRESSION : %s\n", postfix_string);
return 0;
}

/* Function to convert from infix to postfix */


void infix_to_postfix()
{
unsigned int count, temp = 0;
char next;
char symbol;
for(count = 0; count < strlen(infix_string); count++)
{
symbol = infix_string[count]; // Scanning the input expression
if(!check_space(symbol))
{
switch(symbol)
{
case '(': push(symbol);
break;
case ')':
while((next = pop()) != '(') // pop until '(' is encountered
{
postfix_string[temp++] = next;
}
break;
case '+':
case '-':
case '*':
case '/':
case '%':
case '^':
while(!isEmpty() && precedence(stack[top]) >= precedence(symbol)) // Check
precedence and push the higher one
postfix_string[temp++] = pop();
push(symbol);
break;
default:
postfix_string[temp++] = symbol;
}
}
}
while(!isEmpty())
{
postfix_string[temp++] = pop();
}
postfix_string[temp] = '\0';
}

/* Function to check precedence of operators */


int precedence(char symbol)
28
{
switch(symbol)
{
case '(': return 0;
case '+':
case '-':
return 1;
case '*':
case '/':
case '%':
return 2;
case '^':
return 3;
default:
return 0;
}
}

int check_space(char symbol)


{
if(symbol == '\t' || symbol == ' ' )
{
return 1;
}
e l se
{
return 0;
}
}

void push(long int symbol)


{
if(top > 20)
{
printf("Stack Overflow\n");
exit(1);
}
top = top + 1;
stack[top] = symbol; // Push the symbol and make it as TOP
}

int isEmpty()
{
if(top == -1)
{
return 1;
}
e l se
{
return 0;
}
}
29
int pop()
{
if(isEmpty())
{
printf("Stack is Empty\n");
exit(1);
}
return(stack[top--]); // Pop the symbol and decrement TOP
}
Ou tpu t

Enter the valid infix string: (a+b*c)/(d$e) The corresponding


postfix string is: abc*+de$/

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


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

Enter the valid infix string: a+b*c+(d*e+f)*g


The corresponding postfix string is: abc*+de*f+g*+

Re s u l t
Thus the given infix expression was converted into postfix form using stack.
30

E x. No . 6 B i n ary T r e e
Da te :

Aim
To Construct a binary tree.

A l g o r i th m
1. Create a structure with value and 2 pointer variable l for left node and r for
right node.
2. Read the node to be inserted.
3. If it is the first value, the left and right is equal to NULL.
4. Read the left & right child and return the node
5. Stop

P ro g ram

/ * B i n a r y T r e e */

#include <stdio.h>
#include <stdlib.h>
struct btnode
{
int value;
struct btnode *l;
struct btnode *r;
}*root = NULL;
void printout(struct btnode*);
struct btnode* newnode(int);

void main()
{
root=newnode(50);
root->l=newnode(20);
root->r=newnode(30);
root->l->l=newnode(70);
root->l->r=newnode(80);
root->l->r->r=newnode(60);
root->l->l->l=newnode(10);
root->l->l->r=newnode(40);
printf("tree elements are\n");
printf("\nDISPLAYED IN INORDER\n");
printout(root);
printf("\n");
31
}

struct btnode* newnode(int value)


{
struct btnode* node = (struct btnode*)malloc(sizeof(struct btnode));
node->value = value;
node->l = NULL;
node->r = NULL;
return(node);
}

void printout (struct btnode *tree)


{
if (tree->l)
printout(tree->l);
printf("%d->", tree->value);
if (tree->r)
printout(tree->r);
}

OUT P UT : -
tree elements are

DISPLAYED IN INORDER
10->70->40->20->80->60->50->30,

Re s u l t
Thus nodes o f binary t ree will constructed successfully.
32

E x. No . 7 B i n a r y Se a r c h
T re e
Da te :

Aim
To insert and delete nodes in a binary search tree.

A l g o r i th m
1. Create a structure with key and 2 pointer variable left and right.
2. Read the node to be inserted.
If (root==NULL)
root=node
else if (root->key<node
->key)root
->right=NULL
else Root->left=node

3. For Deletion
if it is a leaf node
Remove immediately
Remove pointer between del node & childif it is
having one child
Remove link between del node&child Link delnode is
child with delnodes parent
If it is a node with a children
Find min value in right subtree Copy min
value to delnode placeDelete the duplicate
4. Stop

P ro g ram

/ * B i n a r y S e a r ch T r e e * /

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


struct node
{
33
int key;
struct node *left; struct node *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 ", root->key); inorder(root->right);
}
}

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
node->right = insert(node->right, key); return node;
}

struct node * minValueNode(struct node* node)


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

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


{
struct node *temp; 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)
{
temp = root->right; free(root);
return temp;
}
else if (root->right == NULL)
{
temp = root->left; free(root);
return temp;
}
34
temp = minValueNode(root->right); root->key = temp->key;
root->right = deleteNode(root->right, temp->key);
}
return root;
}

main()
{
struct node *root = NULL; root = insert(root, 50); root = insert(root, 30); root = insert(root,
20); root = insert(root, 40); root = insert(root, 70); root = insert(root, 60); root =
insert(root, 80);
printf("Inorder traversal of the given tree \n"); inorder(root);
printf("\nDelete 20\n"); root = deleteNode(root, 20);
printf("Inorder traversal of the modified tree \n"); inorder(root);
printf("\nDelete 30\n"); root = deleteNode(root, 30);
printf("Inorder traversal of the modified tree \n"); inorder(root);
printf("\nDelete 50\n");
root = deleteNode(root, 50);
printf("Inorder traversal of the modified tree \n"); inorder(root);
}

Ou tpu t

Inorder traversal of the given tree20 30 40 50


60 70 80
Delete 20
Inorder traversal of the modified tree30 40 50 60
70 80
Delete 30
Inorder traversal of the modified tree40 50 60 70
80
Delete 50
Inorder traversal of the modified tree40 60 70 80

Re s u l t
Thus nodes were inserted and deleted from a binary search tree.
35

E x. No . 8 A VL Trees
Da te :

Aim
To perform insertion operation on an AVL tree and to maintain balance factor.

A l g o r i th m
1. Start
2. Perform standard BST insert for w
3. Starting from w, travel up and find the first unbalanced node. Let z be the
first unbalanced node, y be the child of z that comes on the path from w to z
and x bethe grandchild of z that comes on the path from w to z.
4. Re-balance the tree by performing appropriate rotations on the subtree
rooted with z. There can be 4 possible cases that needs to be handled as x, y
and z can bearranged in 4 ways.
a) y is left child of z and x is left child of y (Left Left Case)
b) y is left child of z and x is right child of y (Left Right Case)
c) y is right child of z and x is right child of y (Right Right Case)
d) y is right child of z and x is left child of y (Right Left Case)
5. Stop

P ro g ram

/ * A V L T r e e */

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#define CHANGED 0
#define BALANCED 1
typedef struct bnode
{
int data,bfactor; struct bnode *left; struct bnode *right;
}node;
int height;
void displaymenu()
{
printf("\nBasic Operations in AVL tree");
printf("\n0.Display menu list");
printf("\n1.Insert a node in AVL tree");
36
printf("\n2.View AVL tree"); printf("\n3.Exit");
}
node* getnode()
{
int size;
node *newnode;
size = sizeof(node);
newnode = (node*)malloc(size);
return(newnode);
}
void copynode(node *r, int data)
{
r->data = data;
r->left = NULL;
r->right = NULL;
r->bfactor = 0;
}
void releasenode(node *p)
{
free(p);
}
node* searchnode(node *root, int data)
{
if(root!=NULL)
if(data < root->data)
root = searchnode(root->left, data);
else if(data > root->data)
root = searchnode(root->right, data);
return(root);
}
void lefttoleft(node **pptr, node **aptr)
{
node *p = *pptr, *a = *aptr;
printf("\nLeft to Left AVL rotation"); p->left = a->right;
a->right = p;
if(a->bfactor == 0)
{
p->bfactor = 1;
a->bfactor = -1;
height = BALANCED;
}
e l se
{
p->bfactor = 0;
a->bfactor = 0;
}
p = a;
*pptr = p;
*aptr = a;
}
void lefttoright(node **pptr, node **aptr, node **bptr)
{
node *p = *pptr, *a = *aptr, *b = *bptr;
37
printf("\nLeft to Right AVL rotation");
b = a->right;
b->right = p;
if(b->bfactor == 1)
p->bfactor = -1; else
p->bfactor = 0;
if(b->bfactor == -1)
a->bfactor = 1; else
a->bfactor = 1;
b->bfactor = 0; p = b;
*pptr = p;
*aptr = a;
*bptr = b;
}
void righttoright(node **pptr, node **aptr)
{
node *p = *pptr, *a = *aptr;
printf("\nRight to Right AVL rotation");
p->right = a->left;
a->left = p;
if(a->bfactor == 0)
{
p->bfactor = -1;
a->bfactor = 1;
height = BALANCED;
}
e l se
{
p->bfactor = 0;
a->bfactor = 0;
}
p = a;
*pptr = p;
*aptr = a;
}
void righttoleft(node **pptr, node **aptr, node **bptr)
{
node *p = *pptr, *a = *aptr, *b = *bptr;
printf("\nRight to Left AVL rotation"); b = a->left;
a->left = b->right;
b->right = a;
p->right = b->left;
b->left = p;
if(b->bfactor == -1)
p->bfactor = 1; else
p->bfactor = 0;
if(b->bfactor == -1)
a->bfactor = 0;
b->bfactor = 0; p = b;
*pptr = p;
*aptr = a;
*bptr = b;
}
38
void inorder(node *root)
{
if(root == NULL) return;
inorder(root->left);
printf("\n%4d", root->data);
inorder(root->right);
}
void view(node *root, int level)
{
int k;
if(root == NULL) return;
view(root->right, level+1);
printf("\n");
for(k=0; k<level; k++)
printf(" ");
printf("%d", root->data);
view(root->left, level+1);
}
node* insertnode(int data, node *p)
{
node *a,*b; if(p == NULL)
{
p=getnode(); copynode(p, data);
height = CHANGED; return(p);
}
if(data < p->data)
{
p->left = insertnode(data, p->left);
if(height == CHANGED)
{
switch(p->bfactor)
{
case -1:
p->bfactor = 0;
height = BALANCED; break;
case 0:
p->bfactor = 1;
break;
case 1:
a = p->left;
if(a->bfactor == 1) lefttoleft(&p, &a);
e l se
lefttoright(&p, &a, &b);
height = BALANCED;
break;
}
}
}
if(data > p->data)
{
p->right = insertnode(data, p->right);
if(height == CHANGED)
{
39
switch(p->bfactor)
{
case 1:
p->bfactor = 0;
height = BALANCED;
break;
case 0:
p->bfactor = -1;
break;
case -1:
a=p->right;
if(a->bfactor == -1) righttoright(&p, &a);
e l se
righttoleft(&p, &a, &b);
height=BALANCED; break;
}
}
}
return(p);
}
void main()
{
int data, ch;
char choice = 'y'; node *root = NULL;

displaymenu();
while((choice == 'y') || (choice == 'Y'))
{
printf("\nEnter your choice: "); fflush(stdin);
scanf("%d",&ch); switch(ch)
{
case 0:
displaymenu(); break;
case 1:
printf("Enter the value to be inserted "); scanf("%d", &data);
if(searchnode(root, data) == NULL) root = insertnode(data, root);
e l se
printf("\nData already exists"); break;
case 2:
if(root == NULL)
{
printf("\nAVL tree is empty"); continue;
}
printf("\nInorder traversal of AVL tree"); inorder(root);
printf("\nAVL tree is"); view(root, 1);
break; case 3:
releasenode(root); exit(0);
}
}
getch();
}
40
Ou tpu t

Basic Operations in AVL tree


0.Display menu list
1.Insert a node in2.View AVL tree
AVL tree 3.Exit
Enter your choice:
1
Enter the value to be inserted 1

Enter your choice:Enter 1


the value to be inserted 2

Enter your choice:Enter 1


the value to be inserted 3

Right to Right AVL rotation

Enter your choice:Enter 1


the value to be inserted 4

Enter your choice:Enter 1


the value to be inserted 5

Right to Right AVL rotation


nter your choice: 1
Enter the value to be inserted 6

Right to Right AVL rotationEnter

your choice: 1
Enter the value to be inserted 7Right to

Right AVL rotation

Enter your choice: 1


Enter the value to be inserted 8

Enter your choice: 2


Inorder traversal of AVL tree1
2
3
4
5
6
7
8
AVL tree is
8
7
6
5
41
4
3
2
1
Enter your choice: 3

Re s u l t
Thus rotations were performed as a result of insertions to AVL Tree.

E x. No . 9 B i n ary He ap
Da te :

Aim
To build a binary heap.

A l g o r i th m

1. Start
2. In a heap, for every node x with parent p, the key in p is smaller than or equal
tothe key in x.
3. For insertion operation
a. Add the element to the bottom level of the heap.
b. Compare the added element with its parent; if they are in the
correctorder, stop.
c. If not, swap the element with its parent and return to the previous step.
4. For deleteMin operation
a. Replace the root of the heap with the last element on the last level.
b. Compare the new root with its children; if they are in the correct
order,stop.
c. If not, Swap with its smaller child in a min-heap
5. Stop

/* Priority Queue using Heap */

#include<stdio.h>
#include<math.h>
#define MAX 100

void swap(int*, int*);


void display(int[],int);
42
void insert(int[],int,int,int);
intdel_hi_priori(int[],int,int);

int main()
{
intlb,choice,num,n,a[MAX],data,s;
choice = 0;
n=0; //Represents number of nodes in the queue
lb=0; //Lower bound of the array is initialized to 0
while(choice != 4)
{
printf(".....MAIN MENU.....\n");
printf("\n1.Insert.\n");
printf("2.Delete.\n");
printf("3.Display.\n");
printf("4.Quit.\n");
printf("\nEnter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("Enter data to be inserted : ");
scanf("%d",&data);
insert(a,n,data,lb);
n++;
break;
case 2:
s=del_hi_priori(a,n+1,lb);
if(s!=0)
printf("The deleted value is : %d",s);
if(n>0)
n --;
break;
case 3:
printf("\n");
display(a,n);
break;
case 4:
return 0;
default:
printf("Invalid choice\n");
}
printf("\n\n");
}
return 0;
}

//-------INSERT-------
void insert(int a[],intheapsize,intdata,intlb)
{
inti,p;
int parent(int);
if(heapsize==MAX)
43
{
printf("Queue Is Full!!n");
return;
}
i=lb+heapsize;
a[i]=data;
while(i>lb&&a[p=parent(i)]<a[i])
{
swap(&a[p],&a[i]);
i=p;
}
}

//-------DELETE-------
intdel_hi_priori(int a[],intheapsize,intlb)
{
intdata,i,l,r,max_child,t;
int left(int);
int right(int);
if(heapsize==1)
{
printf("Queue Is Empty!!\n");
return 0;
}
t=a[lb];
swap(&a[lb],&a[heapsize-1]);
i=lb;
heapsize--;
while(1)
{
if((l=left(i))>=heapsize)
break;
if((r=right(i))>=heapsize)
max_child=l;
e l se
max_child=(a[l]>a[r])?l:r;
if(a[i]>=a[max_child])
break;
swap(&a[i],&a[max_child]);
i=max_child;
}
return t;
}

//Returns Parent Index


int parent(int i)
{
float p;
p=((float)i/2.0)-1.0;
return ceil(p);
}

//Return Leftchild Index


44
int left(int i)
{
return 2*i+1;
}

//Return Rightchild Index


int right(int i)
{
return 2*i+2;
}

//-------DISPLAY-------
void display(int a[],int n)
{
int i;
if(n==0)
{
printf("Queue Is Empty!!\n");
return;
}
for(i=0;i<n;i++)
printf("%d ",a[i]);
printf("\n");
}

//-------SWAP-------
void swap(int*p,int*q)
{
int temp;
temp=*p;
*p=*q;
*q=temp;
}
45

E x. No . 1 0 B r e a dt h F i r s t
Se a r c h
Da te :

Aim
To create adjacency matrix of the given graph and to perform breadth first
search traversal.

A l g o r i th m
1. Start
2. Obtain Adjacency matrix for the given graph
3. Define a Queue of size total number of vertices in the graph.
4. Select any vertex as starting point for traversal. Visit that vertex and
insert itinto the Queue.
5. Visit all the adjacent vertices of the vertex which is at front of the Queue
which isnot visited and insert them into the Queue.
6. When there is no new vertex to be visit from the vertex at front of the
Queuethen delete that vertex from the Queue.
7. Repeat step 5 and 6 until queue becomes empty.
8. When queue becomes Empty, then produce final spanning tree by
removingunused edges from the graph.
9. Stop

P ro g ram
/* Graph Traversal – BFS */
#include<stdio.h>
int q[20],front=-1,rear=-1,a[20][20],vis[20];
int delete();
46
void add(int item);
void bfs(int s,int n);
void main()
{
int n,i,s,ch,j;
char c,dummy;
printf("ENTER THE NUMBER VERTICES ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("ENTER 1 IF %d HAS A NODE WITH %d ELSE 0 ",i,j);
scanf("%d",&a[i][j]);
}
}
printf("THE ADJACENCY MATRIX IS\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf(" %d",a[i][j]);
}
printf("\n");
}
do
{
for(i=1;i<=n;i++)
vis[i]=0;
printf("ENTER THE SOURCE VERTEX :");
scanf("%d",&s);
bfs(s,n);
printf("DO U WANT TO CONTINUE(Y/N) ? ");
scanf("%c",&dummy);
scanf("%c",&c);
}
while((c=='y')||(c=='Y'));
}
//**************BFS(breadth-first search) code**************//
void bfs(int s,int n)
{
int p,i;
add(s);
vis[s]=1;
p=delete();
if(p!=0)
printf(" %d",p);
while(p!=0)
{
for(i=1;i<=n;i++)
if((a[p][i]!=0)&&(vis[i]==0))
{
add(i);
vis[i]=1;
}
p=delete();
if(p!=0)
printf(" %d ",p);
47
}
for(i=1;i<=n;i++)
if(vis[i]==0)
bfs(i,n);
}
void add(int item)
{
if(rear==19)
printf("QUEUE FULL");
el se
{
if(rear==-1)
{
q[++rear]=item;
front++;
}
el se
q[++rear]=item;
}
}
int delete()
{
int k;
if((front>rear)||(front==-1))
return(0);
el se
{
k=q[front++];
return(k);
}
}

Re s u l t
Thus Breadth First Traversal is executed on the given graph.
48

E x. No . 1 1 D e p th F i r s t
Se a r c h
Da te :

Aim
To create adjacency matrix of the given graph and to perform depth first
search
traversal.

A l g o r i th m
1. Start
2. Obtain Adjacency matrix for the given graph
3. Define a Stack of size total number of vertices in the graph.
4. Select any vertex as starting point for traversal. Visit that vertex and push it
onto the Stack.
5. Visit any one of the adjacent vertex of the vertex which is at top of the
stackwhich is not visited and push it on to the stack.
6. Repeat step 5 until there are no new vertex to be visit from the vertex on
top ofthe stack.
7. When there is no new vertex to be visit then use back tracking and pop
onevertex from the stack.
8. Repeat steps 5, 6 and 7 until stack becomes Empty.
9. When stack becomes Empty, then produce final spanning tree by
removingunused edges from the graph.
10. Stop
49

P ro g ram
/* DFS on graph */
#include<stdio.h>
int q[20],top=-1,a[20][20],vis[20],stack[20];
void dfs(int s,int n);
void push(int item);
int pop();

void main()
{
int n,i,s,ch,j;
char c,dummy;
printf("ENTER THE NUMBER VERTICES ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("ENTER 1 IF %d HAS A NODE WITH %d ELSE 0 ",i,j);
scanf("%d",&a[i][j]);
}
}
printf("THE ADJACENCY MATRIX IS\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf(" %d",a[i][j]);
}
printf("\n");
}

do
{
for(i=1;i<=n;i++)
vis[i]=0;
printf("ENTER THE SOURCE VERTEX :");
scanf("%d",&s);

dfs(s,n);
printf("DO U WANT TO CONTINUE(Y/N) ? ");
scanf("%c",&dummy);
scanf("%c",&c);
}while((c=='y')||(c=='Y'));
}
//***************DFS(depth-first search) code******************//
void dfs(int s,int n)
{
int i,k;
50
push(s);
vis[s]=1;
k=pop();
if(k!=0)
printf(" %d ",k);
while(k!=0)
{
for(i=1;i<=n;i++)
if((a[k][i]!=0)&&(vis[i]==0))
{
push(i);
vis[i]=1;
}
k=pop();
if(k!=0)
printf(" %d ",k);
}
for(i=1;i<=n;i++)
if(vis[i]==0)
dfs(i,n);
}
void push(int item)
{
if(top==19)
printf("Stack overflow ");
e l se
stack[++top]=item;
}
int pop()
{
int k;
if(top==-1)
return(0);
e l se
{
k=stack[top--];
return(k);
}
}

Re s u l t
Thus depth first traversal is executed on the given graph.
51

E x. No . 1 2 A p p l i c a t i o n o f G r a p h - D i j k s t r a ’ s S h o r t e s t P a th
Da te :

Aim
To find the shortest path for the given graph from a specified source to all
other
vertices using Dijkstra’s algorithm.

A l g o r i th m
1. Start
2. Obtain no. of vertices and adjacency matrix for the given graph
3. Create cost matrix from adjacency matrix. C[i][j] is the cost of going
from vertex i to vertex j. If there is no edge between vertices i and j then
C[i][j] isinfinity
4. Initialize visited[] to zero
5. Read source vertex and mark it as visited
6. Create the distance matrix, by storing the cost of vertices from vertex no. 0 to
n-1from the source vertex
distance[i]=cost[0][i];
7. Choose a vertex w, such that distance[w] is minimum and visited[w] is 0.
Markvisited[w] as 1.
8. Recalculate the shortest distance of remaining vertices from the source.
52
9. Only, the vertices not marked as 1 in array visited[ ] should be considered
forrecalculation of distance. i.e. for each vertex v
if(visited[v]==0)
distance[v]=min(distance[v]
distance[w]+cost[w][v])
10. Stop
53

P ro g ram

/* Dijkstra’s Shortest Path */

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

#define INFINITY 9999


#define MAX 10

void dijkstra(int G[MAX][MAX], int n, int startnode);main()


{
int G[MAX][MAX], i, j, n, u; printf("Enter no. of
vertices: ");scanf("%d", &n);
printf("Enter the adjacency matrix:\n");for(i=0; i<n;
i ++)
for(j=0; j<n; j++) scanf("%d", &G[i][j]);
printf("Enter the starting node: ");scanf("%d", &u);
dijkstra(G, n, u);
}

void dijkstra(int G[MAX][MAX], int n,int startnode)


{
int cost[MAX][MAX], distance[MAX], pred[MAX];
int visited[MAX],count, mindistance, nextnode, i, j;for(i=0; i<n; i++)
for(j=0; j<n; j++) if(G[i][j]
== 0)
cost[i][j] = INFINITY;
e lse
cost[i][j] = G[i][j];
for(i=0; i<n; i++)
{
distance[i] = cost[startnode][i];pred[i] =
startnode;
visited[i] = 0;
}
distance[startnode] = 0;
visited[startnode] = 1;
count = 1; while(count
< n-1)
{
mindistance = INFINITY;
for(i=0; i<n; i++)
if(distance[i] < mindistance && !visited[i])
{
54

mindistance = distance[i];nextnode=i;
}
visited[nextnode] = 1;for(i=0;
i < n ; i ++)
if(!visited[i])
if(mindistance + cost[nextnode][i] <
distance[i])
{

distance[i] = mindistance +
cost[nextnode][i];pred[i] =
nextnode;
count++; }
}
55
for(i=0; i<n; i++) if(i !=
startnode)
{
printf("\nDistance to node%d = %d", i,
distance[i]);
printf("\nPath = %d", i);j = i;
do
{
j = pred[j]; printf("<-%d",
j);
} while(j != startnode);
}
}

Ou tpu t

Enter no. of vertices: 5 Enter the


adjacency matrix:0 10 0 30 100
10 0 50 0 0
0 50 0 20 10
30 0 20 0 60
100 0 0 60 0
Enter the starting node: 0Distance
to node1 = 10 Path = 1<-0
Distance to node2 = 50Path
= 2<-3<-0
Distance to node3 = 30Path
= 3 < -0
Distance to node4 = 60Path
= 4<-2<-3<-0

Re s u l t
Thus Dijkstra's algorithm is used to find shortest path from a given vertex.
56
E x. No . 1 3 a Li n e ar
S e a r ch Da t e :

Aim
To perform linear search of an element on the given array.

A l g o r i th m
1 . S ta r t
2 . Re ad n u mbe r o f a r r a y e l e m e n t s n
3 . R e a d a r r a y e l e m e n ts A i , i = 0 , 1 , 2 , … n – 1
4 . R e a d s e a r ch v a l u e
5 . A s s i g n 0 to f o u n d
6 . C h e ck e a ch a r r a y e l e m e n t a g a i n s t s e a r c h
If A i = s e arch th e n

fo u n d = 1

P r i n t "E l e m e n t f o u n d"
P r i n t po s i t i o n i
S to p
7 . I f fo u n d = 0 t h e n
pri n t " E l e me n t n o t f o u n d "
8 . S to p
57

P ro g ram

/ * L i n e a r s e a r c h o n a s o r te d a r r a y */ #i n c l u d e

< s t di o . h >
#i n cl u de < con i o . h >

mai n( )
{
i n t a [5 0 ] , i , n , v a l , f o u n d ; c l r s c r ( ) ;

p r i n t f ( " E n t e r n u m b e r o f e l e m e n t s : " ) ; s c a n f ( " % d" ,


&n);
p r i n tf ( "E n te r A r r a y E l e m e n ts : \ n " ) ; f o r ( i = 0 ; i < n ;
i + +)
s ca n f( " % d" , & a [ i ] ) ;

p r i n t f ( " E n t e r e l e m e n t t o l o c a t e : " ) ; s c a n f ( " % d" ,


& va l ) ;
f o u n d = 0 ; fo r ( i = 0 ; i < n ;
i ++)
{
i f ( a [i ] = = va l )
{
p r i n tf ( "E l e m e n t fo u n d a t po s i t i o n % d ", i ) ; fo u n d = 1 ;
b re a k;
}
}
i f ( fo u n d = = 0 )
p r i n t f ( " \ n E l e m e n t n o t f o u n d" ) ; g e t c h ( ) ;
}

Ou tpu t

E n te r n u m b e r o f e l e m e n ts : 7 E n te r
A r r a y E l e m e n ts :
23 6 12 5 0 32 10
E n te r e l e m e n t t o l o c a te : 5 E l e m e n t
fo u n d a t po s i t i o n 3

Re s u l t
T h u s a n a r r a y w a s l i n e a r l y s e a r ch e d f o r a n e l e m e n t ' s e x i s t e n c e .
58

E x. No . 1 3 b Bi n ar y
Se a r c h Da t e :

Aim
T o l o ca t e a n e l e m e n t i n a s o r t e d a r r a y u s i n g B i n a r y s e a r ch m e t h o d

A l g o r i th m
1 . S ta r t
2 . Re ad n u m b e r o f a r r a y e l e m e n t s , s a y n
3 . Cr e a te a n a r r a y a r r c o n s i s t i n g n s o r t e d e l e m e n t s
4 . G e t e l e m e n t , s a y k e y t o be l o ca t e d
5 . A s s i g n 0 to l o w e r a n d n t o u pp e r
6 . W h i l e ( l o w e r < u pp e r )
D e t e r m i n e m i ddl e e l e m e n t m i d =
( u pp e r + l o w e r )/ 2 I f ke y = a r r [ m i d ] th e n
P ri n t mi d
St o p
E l s e i f k e y > arr[mi d]
th e n l o we r = m i d +
1
else
u pp e r = m i d – 1

7 . P r i n t "E l e m e n t n o t f o u n d"
8 . S to p
59

P ro g ram

/ * B i n a r y S e a r c h o n a s o r t e d a r r a y * / # i n c l u de

< s td i o . h >
#i n cl u de < con i o . h >

mai n( )
{
i n t a [5 0 ] , i , n , u p p e r , l o w e r , m i d , v a l , f o u n d; c l r s c r ( ) ;

p r i n tf ( "E n te r a r r a y s i z e : ") ; s c a n f( "% d ",


& n );
f o r ( i = 0 ; i < n ; i + + ) a [i ] = 2
* i;

p r i n t f ( " \ n E l e m e n t s i n S o r t e d O r de r \ n " ) ; f o r ( i = 0 ; i < n ;


i ++)
p r i n t f ( "% 4 d" , a [ i ] ) ;

p r i n t f ( " \ n E n t e r e l e m e n t t o l o c a t e : " ) ; s c a n f ( " % d" ,


& va l ) ;
u pp e r = n ;
l o we r = 0 ;
fo u n d = - 1 ;
w h i l e ( l o w e r < = u pp e r )
{
mi d = ( u ppe r + l o w e r)/ 2 ; i f
( a [ m i d] = = v a l )
{
p r i n t f ( " L o c a t e d a t p o s i t i o n % d" , m i d ) ; f o u n d = 1 ;
b re a k;
}
e l s e i f ( a [m i d ] > va l ) u p p e r =
mi d - 1 ;
else
l owe r = mi d + 1 ;
}

i f ( fo u n d = = - 1 ) pr i n t f( " E l e m e n t n o t
f o u n d" ) ;
g e t ch ( ) ;
}
60

Ou tpu t

E n te r a r r a y s i z e : 9 E l e m e n t s i n
So rt e d O rde r
0 2 4 6 8 10 12 14 16
E n te r e l e m e n t t o l o c a te : 1 2 L o ca t e d
a t p o s i ti o n 6

E n te r a r r a y s i z e : 1 0 E l e m e n t s i n
So rt e d O rde r
0 2 4 6 8 10 12 14 16 18
E n te r e l e m e n t t o l o c a te : 1 3 E l e m e n t
n o t fo u n d

Re s u l t
61
T h u s a n e l e m e n t i s l o c a t e d q u i ck l y u s i n g b i n a r y s e a r ch m e t h o d .
62

E x. No . 1 3 c B u b bl e
S o r t D a te :

Aim
T o s o r t a n a r r a y o f N n u m b e r s u s i n g B u b bl e s o r t .

A l g o r i th m
1 . S ta r t
2 . Re ad n u mbe r o f a r r a y e l e m e n t s n
3 . R e a d a r r a y e l e m e n ts A i
4 . I n de x i va r i e s f r o m 0 t o n - 2
5 . I n de x j v a r i e s f r o m i + 1 t o n - 1
6 . T r a v e r s e t h e a r r a y a n d c o m p a r e e a ch p a i r o f
e l e m e n ts I f A i > A j th e n
Swa p A i a n d A

7 . S to p
63

P ro g ram

/ * B u bb l e S o r t * /

# i n c l u d e < s t di o . h > # i n cl u d e
< con i o .h >

mai n( )
{
i n t a [5 0 ] , i , j , n , t ; c l r s c r ( ) ;
p r i n t f ( " E n t e r n u m b e r o f e l e m e n t s : " ) ; s c a n f ( " % d" ,
&n);
p r i n t f ( "E n t e r A r r a y E l e m e n t s \ n ") ; f o r ( i = 0 ; i < n ;
i + +)
s ca n f( " % d" , & a [ i ] ) ;

fo r ( i = 0 ; i < n - 1 ; i + + )
{
fo r ( j = i + 1 ; j < n ; j + + )
{
i f ( a [i ] > a [ j ])
{
t = a [i ]; a [ i ] = a [ j ] ;
a[j] = t;
}
}
}

p r i n t f ( " \ n E l e m e n t s i n S o r t e d o r de r : " ) ; f o r ( i = 0 ; i < n ;


i ++)
p r i n tf ( "% d ", a [ i ] ) ; g e tc h ( ) ;
}

Ou tpu t

E n te r n u m b e r o f e l e m e n ts : 5 E n te r
A r r a y E l e m e n ts
3 7 -9 0 2

E l e m e n t s i n So rt e d o rde r :
-9 0 2 3 7

Re s u l t
T h u s a n a r r a y w a s s o r te d u s i n g b u bb l e s o r t .
64

E x. No . 1 3 d Qu i c k So rt
Da t e :

Aim
T o s o r t a n a r r a y o f N n u m b e r s u s i n g Q u i c k s o r t.

A l g o r i th m
1 . S ta r t
2 . Re ad n u mbe r o f a r r a y e l e m e n t s n
3 . R e a d a r r a y e l e m e n ts A i
4 . S e l e c t a n p i v o t e l e m e n t x fr o m A i
5 . D i vi de t h e a r r a y i n t o 3 s e q u e n c e s : e l e m e n t s < x , x , e l e m e n t s > x
6 . R e c u r s i ve l y q u i c k s o r t b o t h s e t s ( A i < x a n d A i > x )
7 . S to p
65

P ro g ram

/ * Q u i ck S o r t * /

# i n c l u d e < s t di o . h > # i n cl u d e
< con i o .h >

vo i d q s o r t ( i n t a r r [2 0 ] , i n t f s t , i n t l a s t ) ; m a i n ( )
{
int arr[30];int i,
s i ze ;
p r i n t f ( " E n t e r t o t a l n o . o f t h e e l e m e n t s : " ) ; s c a n f ( " % d" , & s i z e ) ;
p r i n tf ( "E n te r t o ta l % d e l e m e n t s : \ n ", s i z e ) ; fo r ( i = 0 ; i < s i z e ;
i ++)
s ca n f ( " % d" , & a r r [i ]) ;
q s o r t( a r r , 0 , s i z e - 1 ) ;
p r i n tf ( "\ n Q u i ck s o r t e d e l e m e n ts \ n ") ; fo r ( i = 0 ;
i < s i ze ; i ++)
p r i n t f ( "% d \ t " , a r r [i ]) ; g e t c h ( ) ;
}

vo i d q s o r t ( i n t a r r [2 0 ] , i n t f s t , i n t l a s t )
{
i n t i , j , p i v o t, t m p ; i f( f s t < l a s t )
{
p i v o t = fs t; i =
fs t ;
j = l as t; wh i l e (i
< j)
{
w h i l e ( a r r [i ] < = a r r [ p i v o t ] & & i < l a s t ) i + + ;
w h i l e ( a r r [j ] > a r r [ p i v o t ] ) j - - ;
i f(i <j )
{
tmp = arr[i ]; a rr[i ] =
a r r [ j ] ; a r r [j ] = t m p ;
}
}
t m p = a r r [ p i vo t ]; a r r [p i v o t ] =
a r r [ j ] ; a r r [ j ] = tm p ; q s o r t ( a r r ,
f s t , j - 1 ) ; q s o r t( a r r , j + 1 , l a s t ) ;
66

}
}

Ou tpu t

E n te r t o ta l n o . of th e e l e m e n t s : 8 E n te r t o ta l 8
e l e m e nts :
1
2
7
-1
0
4
-2
3

Q u i ck s o r t e d e l e m e n ts
-2 -1 0 1 2 3 4 7

Re s u l t
67
T h u s a n a r r a y w a s s o r te d u s i n g q u i c k s o r t ' s d i v i d e a n d c o n q u e r m e t h o d .
68

E x. No . 1 3 e M e rg e
S o r t Da t e :

Aim
T o s o r t a n a r r a y o f N n u m b e r s u s i n g M e r g e s o r t.

A l g o r i th m
1 . S ta r t
2 . Re ad n u mbe r o f a r r a y e l e m e n t s n
3 . R e a d a r r a y e l e m e n ts A i
4 . D i vi de t h e a r r a y i n t o s u b - a r r a y s w i t h a s e t o f e l e m e n t s
5 . R e cu r s i v e l y s o r t t h e s u b - a r r a y s
6 . M e r g e th e s o r te d s u b - a r r a y s o n t o a s i n g l e s o r t e d a r r a y .
7 . S to p
69

P ro g ram

/ * M e r g e s o r t */

# i n c l u d e < s t di o . h > # i n cl u d e
< con i o .h >

vo i d m e r g e ( i n t [] , i n t , i n t , i n t ) ; v o i d p a r t ( i n t
[ ], i n t , i n t ) ;
i n t s i ze ;

mai n( )
{
i n t i , arr[3 0 ];
p r i n tf ( "E n te r t o ta l n o . o f e l e m e n t s : ") ; s c a n f ( "% d ",
& s i ze );
p r i n tf ( "E n te r a r r a y e l e m e n ts : " ) ; fo r ( i = 0 ;
i < s i ze ; i + + )
s ca n f ( " % d" , & a r r [i ]) ;
p a r t( a r r , 0 , s i z e - 1 ) ;
p r i n tf ( "\ n M e r g e s o r t e d l i s t : ") ; fo r ( i = 0 ; i < s i z e ;
i ++ )
p r i n t f ( "% d ", a r r [ i ] ) ; g e t c h ( ) ;
}

vo i d p a r t ( i n t a r r [ ], i n t m i n , i n t m a x )
{
i n t i , m i d; i f ( m i n
< m a x)
{
mi d = ( mi n + max) / 2 ; part( arr,
m i n , m i d ) ; p a r t ( a r r , m i d+ 1 , m a x ) ;
me rg e ( ar r, mi n , m i d, max);
}
i f ( max- mi n = = ( s i ze / 2 )- 1 )
{
p r i n tf ( "\ n H a l f s o r t e d l i s t : ") ; fo r ( i = m i n ;
i < = max; i ++ )
p r i n t f ( " % d " , a r r [i ]) ;
}
}

vo i d m e r g e ( i n t a r r [ ] , i n t m i n , i n t m i d , i n t m a x)
{
i n t t m p [ 3 0 ]; i n t i , j , k ,
m; j = mi n ;
m = mid + 1;
70

fo r ( i = m i n ; j < = m i d & & m < = m a x ; i + + )


{
i f( arr[j] < = arr[m])
{
t m p [ i ] = a r r [j ] ; j + + ;
}
else
{
t m p [ i ] = a r r [m ]; m + + ;
}
}
i f ( j > m i d)
{
fo r ( k = m ; k< = m a x ; k+ + )
{
t m p [ i ] = a r r [k ] ; i + + ;
}
}
else
{
fo r ( k = j ; k< = m i d ; k+ + )
{
t m p [ i ] = a r r [k ] ; i + + ;
}
}
fo r ( k = m i n ; k < = m a x ; k + + ) a r r [ k ]
= t m p [ k ];
}

Ou tpu t

E n te r t o ta l n o . of e l e m e n t s : 8
E n te r a r r a y e l e m e n ts : 2 4 1 3 2 6 1 2 2 7 3 8 1 5

Hal f s o rte d l i s t : 1 1 3 2 4 2 6
Hal f s o rte d l i s t : 2 1 5 2 7 3 8
M e rg e s o rte d l i s t : 1 2 1 3 1 5 2 4 2 6 2 7 3 8

Re s u l t
T h u s a r r a y e l e m e n ts w a s s o r t e d u s i n g m e r g e s o r t ' s d i v i de a n d co n q u e r
m e t h o d.
71

E x. No . 1 3 f I n s e r ti o n
S o r t Da t e :

Aim
T o s o r t a n a r r a y o f N n u m b e r s u s i n g I n s e r ti o n s o r t.

A l g o r i th m
1 . S ta r t
2 . Re ad n u mbe r o f a r r a y e l e m e n t s n
3 . R e a d a r r a y e l e m e n ts A i
4 . S o r t th e e l e m e n t s u s i n g i n s e r t i o n s o r t
I n pa s s p , m o v e th e e l e m e n t i n p o s i ti o n p l e ft u n t i l i ts co r r e ct pl a ce i s
fo u n d a m o n g t h e f i r s t p + 1 e l e m e n t s .
E l e m e n t a t po s i t i o n p i s s a v e d i n te m p, a n d a l l l a r g e r e l e m e n ts
( p r i o r t o po s i t i o n p ) a r e m o v e d o n e s po t to t h e r i g h t. T h e n te m p i s
p l a c e d i n t h e co r r e c t s p o t.
5 . S to
72

P ro g ram

/ * I n s e r t i o n So r t */ m a i n ( )
{
i n t i , j , k , n , te m p , a [ 2 0 ] , p= 0 ;

p r i n t f ( "E n t e r t o ta l e l e m e n t s : " ) ; s c a n f ( " % d " , & n ) ;


p r i n t f ( "E n t e r a r r a y e l e m e n t s : " ) ; f o r ( i = 0 ; i < n ; i + + )
s ca n f( " % d" , & a [ i ] ) ;

fo r ( i = 1 ; i < n ; i + + )
{
t e m p = a [i ]; j = i - 1 ;
w h i l e ( ( te m p < a [j ]) & & ( j > = 0 ) )
{
a [ j + 1 ] = a [ j ]; j = j - 1 ;
}
a [ j + 1 ] = te m p;

p++;
p r i n tf ( "\ n A ft e r P a s s % d : ", p ) ; fo r ( k= 0 ; k < n ; k + + )
p r i n tf ( " % d ", a [ k] ) ;
}

p r i n tf ( "\ n S o r t e d L i s t : " ) ; f o r ( i = 0 ; i < n ; i + + )


p r i n tf ( " % d ", a [ i ] ) ;
}

Ou tpu t

E n te r t o ta l e l e m e n t s : 6 E n te r
a r r a y e l e m e n ts : 3 4 8 64 51 32 21
A ft e r P a s s 1 : 8 34 64 51 32 21
A ft e r P a s s 2 : 8 34 64 51 32 21
A ft e r P a s s 3 : 8 34 51 64 32 21
A ft e r P a s s 4 : 8 32 34 51 64 21
A ft e r P a s s 5 : 8 21 32 34 51 64
So rt e d Li s t : 8 21 32 34 51 64

Re s u l t
T h u s a r r a y e l e m e n ts w a s s o r t e d u s i n g i n s e r t i o n s o r t .
P r o g r a m N a m e : - P r i n t th e A l t e r n a te N o de s i n a L i n k e d L i s t

INPUT:-

#include <stdio.h>
73

#include <stdlib.h>

struct node

int a;

struct node *next;

};

void generate(struct node **);

void display(struct node *);

void delete(struct node **);

int main()

struct node *head = NULL;

generate(&head);

printf("\nDisplaying the alternate nodes\n");

display(head);

delete(&head);

return 0;

void display(struct node *head)

static int flag = 0;


74

if(head != NULL)

if (!(flag % 2))

printf("%d ", head->a);

flag++;

display(head->next);

void generate(struct node **head)

i nt nu m, i ;

struct node *temp;

printf("Enter length of list: ");

scanf("%d", &num);

for (i = num; i > 0; i--)

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

temp->a = i;

if (*head == NULL)

*head = temp;

(*head)->next = NULL;
75

e l se

temp->next = *head;

*head = temp;

void delete(struct node **head)

struct node *temp;

while (*head != NULL)

temp = *head;

*head = (*head)->next;

free(temp);

OUTPUT:-

Enter length of list: 10


76

Displaying the alternate nodes

1 3 5 7 9

You might also like