0% found this document useful (0 votes)
60 views102 pages

DS Record

The document describes a C program to implement a circular queue using an array. It defines functions for enqueue, dequeue and display operations. The enqueue function checks if the queue is full before inserting an element. If full, it displays an error message, otherwise inserts the element. The dequeue function checks if the queue is empty before removing an element. If empty, it displays an error, otherwise removes an element. The display function prints all elements in the queue.

Uploaded by

hahahnew9
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)
60 views102 pages

DS Record

The document describes a C program to implement a circular queue using an array. It defines functions for enqueue, dequeue and display operations. The enqueue function checks if the queue is full before inserting an element. If full, it displays an error message, otherwise inserts the element. The dequeue function checks if the queue is empty before removing an element. If empty, it displays an error, otherwise removes an element. The display function prints all elements in the queue.

Uploaded by

hahahnew9
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/ 102

PPG INSTITUTE OF TECHNOLOGY

COIMBATORE – 641 035

CS3311- DATA STRUCTURES LABORATORY

Department of

COMPUTER SCIENCE AND ENGINEERING


PPG INSTITUTE OF TECHNOLOGY
COIMBATORE – 641 035

CS3311- DATA STRUCTURES


LABORATORY

NAME:......................................................... ROLL NO: ....................................

SEMESTER: .............................................. BRANCH: .....................................

...............................................................................................................................

Certified bonafide record of work done by.............................................................

Place: COIMBATORE Date:

Staff In-Charge Head of the Department

University Register Number: .....................................................................................

Submitted for the University Practical Examination held on.....................................

INTERNAL EXAMINER EXTERNAL EXAMINER


CONTENTS
s

Page
S.No Date Title Marks Signature
No.
s

1(a) Array Implementation of Stack 1

1(b) Array Implementation of Queue 6

Array Implementation of Circular


1(c) 10
Queue

2 Implementation of Singly Linked List 14

3(a) Linked List Implementation of Stack 20

Linked List Implementation of Linear


3(b) 27
Queue ADT

Implementation of Polynomial
4 32
Manipulation Using Linked List

5(a) Evaluating Postfix Expressions 38

Implementation of Infix to Postfix


5(b) 43
Conversion

Implementation of Binary Search


6 47
Tree
CONTENTS
s

Page
S.No Date Title Marks Signature
No.
s

7 Implementation of AVL Tree 57

Implementation of Heaps Using


8 66
Priority Queues

Implementation of Dijkstra’s
9 69
Algorithm

10 Implementation of Prim’s Algorithm 74

11(a) Implementation of Linear Search 78

11(b) Implementation of Binary Search 81

12(a) Implementation of Insertion Sort 84

12(b) Implementation of Selection Sort 87

13 Implementation of Merge Sort 90

14 Implementation of Open Addressing 94


Ex.No : 1a
ARRAY IMPLEMENTATION OF STACK
Date :

AIM
To write a C program to perform array implementation of stack.

ALGORITHM

1. Start the program.


2. Include all the header files which are used in the program and define a
3. Constant 'SIZE' with specific value.

4. Declare all the functions used in stack implementation.


5. Create a one dimensional array with fixed size (int stack[SIZE])
6. Define a integer variable 'top' and initialize with '-1'. (int top = -1)
7. In main method display menu with list of operations and make suitable function calls to
perform operation selected by the user on the stack.

PROGRAM

#include<stdio.h>

int stack[100],choice,n,top,x,i;
void push(void);
void pop(void);
void display(void);
int main()
{
top=-1;
printf("\n Enter the size of STACK[MAX=100]:");
scanf("%d",&n);
printf("\n\t STACK OPERATIONS USING ARRAY");
printf("\n\t 1.PUSH\n\t 2.POP\n\t 3.DISPLAY\n\t 4.EXIT");

do
{

printf("\n Enter the Choice:");

1|Page 711721104 095


scanf("%d",&choice);
switch(choice)
{
case 1:
{

push();
break;
}

case 2:
{

pop();
break;
}
case 3:
{
display();
break;

}
case 4:
{
printf("\n\t EXIT POINT ");

break;
}

default:
{
printf ("\n\t Please Enter a Valid Choice(1/2/3/4)");
}
}

}
while(choice!=4);
return 0;

2|Page
}
void push()
{

if(top>=n-1)
{
printf("\n\tSTACK is over flow");
}

else
{
printf(" Enter a value to be pushed:");
scanf("%d",&x);

top++;
stack[top]=x;
}
}
void pop()

{
if(top<=-1)
{
printf("\n\t Stack is under flow");
}
else

{
printf("\n\t The popped elements is %d",stack[top]);
top--;
}
}
void display()
{
if(top>=0)
{

3|Page
printf("\n The elements in STACK \n");
for(i=top; i>=0; i--)
printf("\n%d",stack[i]);
printf("\n Press Next Choice");
}
else
{

printf("\n The STACK is empty");


}
}

4|Page
OUTPUT

RESULT
Thus the array implementation of stack program was executed successfully.
5|Page
Ex.No : 1b
ARRAY IMPLEMENTATION OF QUEUE
Date :

AIM
To write a C program to perform array implementation of queue.

ALGORITHM

1. Start the program.


2. Include all the header files which are used in the program and define a constant
'SIZE' with specific value.
3. Declare all the user defined functions which are used in queue implementation.
4. Create a one dimensional array with above defined SIZE (int queue[SIZE])
5. Define two integer variables 'front' and 'rear' and initialize both with '-1'. (int front = -1, rear = -1)
6. Then implement main method by displaying menu of operations list and make suitable
function calls to perform operation selected by the user on queue

PROGRAM

#include <stdio.h>
#include<stdlib.h>
#define MAX 50

int queue_array[MAX];
int rear = - 1, front = - 1;
void insert(void);

void delete(void);
void display(void);
void main()
{
int choice;
while (1)
{

printf("1.Insert element to queue \n");


printf("2.Delete element from queue \n");

6|Page
printf("3.Display all elements of queue \n");
printf("4.Quit \n");
printf("Enter your choice : ");
scanf("%d", &choice);
switch (choice)
{
case 1:

insert();
break;
case 2:

delete();
break;
case 3:

display();
break;
case 4:

exit(1);
default:
printf("Wrong choice \n");
}}}
void insert()
{

int add_item;
if (rear == MAX - 1)
printf("Queue Overflow \n");
else

{
if (front == - 1)

/*If queue is initially empty */


front = 0;
printf("Inset the element in queue : ");

7|Page
scanf("%d", &add_item);
rear = rear + 1;
queue_array[rear] = add_item;
}
}

void delete()
{
if (front == - 1 || front > rear)
{printf("Queue Underflow \n");
}

else
{
printf("Element deleted from queue is : %d\n", queue_array[front]);
front = front + 1;

}
} /*End of delete() */
void display()

{
int i;

if (front == - 1)
printf("Queue is empty \n");
else
{
printf("Queue is : \n");
for (i = front; i<= rear; i++)
printf("%d ", queue_array[i]);
printf("\n");

}
}

8|Page
OUTPUT

RESULT
Thus the program for array implementation of Queue was executed successfully.
9|Page
Ex.No : 1c
ARRAY IMPLEMENTATION OF CIRCULAR QUEUE
Date :

AIM
To write a C program to perform array implementation of Circular queue

ALGORITHM

1. Start the program


2. To Enqueue an element into the circular queue, Check whether queue is Full – Check
((rear == SIZE-1 && front == 0) || (rear== front-1)).
3. If it is full then display Queue is full. If queue is not full then, check if (rear == SIZE – 1
&& front != 0) if it is true then set rear=0 and insert element.
4. To Dequeue an element from the circular queue, Check whether queue is Empty means
check (front==-1).
5. If it is empty then display Queue is empty. If queue is not empty then step 3
6. Check if (front==rear) if it is true then set front=rear= -1 else check if (front==size-1), if it
is true then set front=0 and return the element

PROGRAM

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#define size 5
int main()
{
int arr[size],Rear=-1,Front=0,temp=0,ch,n,i,x;
for(;;)
{

printf("1. Enqueue\n");
printf("2. Dequeue\n");
printf("3. Display\n");
printf("4. Exit\n");
printf("Enter Choice: ");

10 | P a g e
scanf("%d",&ch);
switch(ch)
{
case 1:
if(temp==size)

{
printf("Queue is full");
getch(); // pause the loop to see the message
}
else

{
printf("Enter a number ");
scanf("%d",&n);
Rear=(Rear+1)%size;
arr[Rear]=n;
temp=temp+1;
}
break;
case 2:
if(temp==0)
{
printf("Queue is empty");

getch(); // pause the loop to see the message


}
else
{
printf("Number Deleted = %d",arr[Front]);
Front=(Front+1)%size;
temp=temp-1;
getch(); // pause the loop to see the number
}

11 | P a g e
break;
case 3:
if(temp==0)
{
printf("Queue is empty");

getch(); // pause the loop to see the message


}
else
{
x=Front;

for(i=1; i<=temp; i++)


{
printf("%d ",arr[x]);
x=(x+1)%size;

}
getch(); // pause the loop to see the numbers

}
break;
case 4:
exit(0);
break;
default:
printf("Wrong Choice");

getch(); // pause the loop to see the message


}
}
return 0;
}

12 | P a g e
OUTPUT

RESULT

Thus the program for array implementation of circular queue was executed successfully.

13 | P a g e
Ex.No : 02
IMPLEMENTATION OF SINGLY LINKED LIST
Date :

AIM
To write a C program to implement Singly Linked List.

ALGORITHM
1. Start the program.
2. Create a list with the menus 1) Insertion 2) Deletion 3) Display and 4) Quit in the list.
Read the option from the user. Also define the structure nodes and member functions.
3. For insertion find the right position in the list and insert the element.
4. Make necessary pointer changes after insertion.
5. For deletion find the item in the list and delete the element. If the list is empty, print an error
message as “List is Empty”.
6. Make necessary pointer changes after deletion.
7. Display the contents of the list.
.
PROGRAM
#include <stdio.h>
#include <stdlib.h>
struct node

{
int data;
struct node *link;
};
struct node *start=NULL;
struct node *temp,*prev, *nod;
void insert(struct node *);
void delet();
void display();
int main(void)

{
int opt;

14 | P a g e
clrscr();

do

{
printf("\n 1.Insert element into a singly linked list\n");
printf("\n 2.Delete element from a singly linked list\n");
printf("\n 3.Display list\n");
printf("\n 4.Quit\n");
printf("\nEnter option: ");
scanf("%d",&opt);
switch(opt)
{
case 1:

nod=(struct node *)calloc(1,sizeof(struct node));


insert(nod);
break;
case 2:

delet();
break;
case 3:
display();
break;
case 4:

exit(1);
}
} while(1);
}
void insert(struct node *n)
{

int item;
printf("\nEnter the element that has to be inserted:");

15 | P a g e
scanf("%d",&item);
n->data=item;
if(start==NULL)
{
start= n;
n->link =0;
}
else

{
temp = start;
while (temp != 0)

{
if (temp->data < item)
{
prev = temp;
temp = temp->link;

}
else break;
}
if (temp == start)
{
n->link = temp;
start = n;

}
else

{
prev->link = n;
n->link = temp;
}
}
}

16 | P a g e
void delet()
{
int item;

printf("\nEnter the element that has to be deleted: ");


scanf("%d",&item);

if(start==NULL)
printf("\n List is empty! No deletion possible! \n");
else

{
temp = start;
while (temp != 0)

{
if (temp->data == item) break;
else

{
prev = temp;

temp = temp->link;
}
}
if (temp == start)
{
start = temp->link;
free(temp);

}
else
{
if (temp == 0)
{

printf(" Item not found in the list\n");}


else
{

17 | P a g e
prev->link = temp->link;
free(temp);
}
}
}

}
void display()
{
if(start == NULL)
printf("\n List is empty! \n");
else

{
printf("contents of the List: \n");
temp=start;

while(temp->link !=0)
{

printf("\n %d ",temp->data);
temp=temp->link;
}
printf("\n %d ",temp->data);
}
}

18 | P a g e
OUTPUT

RESULT

Thus the program for implementation of Singly Linked list was executed successfully.

19 | P a g e
Ex.No : 3a
LINKED LIST IMPLEMENTATION OF STACK
Date :

AIM
To write a C program to perform Linked List implementation of stack.

ALGORITHM

1. Start the program


2. Include all the header files which are used in the program. And declare all the user
defined functions.
3. Define a 'Node' structure with two members data and next.
4. Define a Node pointer 'top' and set it to NULL.
5. Implement the main method by displaying Menu with list of operations and make
suitable function calls in the main method.
6. Create a newNode with given value.
7. Check whether stack is Empty (top == NULL)
8. If it is Empty, then set newNode→next = NULL.
9. If it is Not Empty, then set newNode→next = top.
10. Finally, set top = newNode.

PROGRAM

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

{
int info;
struct node *ptr;
}*top,*top1,*temp;
int topelement();
void push(int data);
void pop();
void empty();
void display();

20 | P a g e
void destroy();
void stack_count();
void create();
int count = 0;
void main()
{
int no, ch, e;
printf("\n 1 - Push");

printf("\n 2 - Pop");
printf("\n 3 - Top");
printf("\n 4 - Empty");
printf("\n 5 - Exit");
printf("\n 6 - Dipslay");
printf("\n 7 - Stack Count");
printf("\n 8 - Destroy stack");
create();
while (1)
{
printf("\n Enter choice : ");
scanf("%d", &ch);

switch (ch)
{
case 1:
printf("Enter data : ");
scanf("%d", &no);
push(no);

break;
case 2:
pop();
break;
case 3:

21 | P a g e
if (top == NULL)
printf("No elements in stack");

else
{
e = topelement();

printf("\n Top element : %d", e);


}

break;
case 4:
empty();
break;
case 5:
exit(0);
case 6:
display();
break;
case 7:

stack_count();
break;
case 8:
destroy();
break;
default :

printf(" Wrong choice, Please enter correct choice ");


break;
}

}
}
void create()
{
top = NULL;

22 | P a g e
}
void stack_count()
{

printf("\n No. of elements in stack : %d", count);


}
void push(int data)
{

if (top == NULL)
{
top =(struct node *)malloc(1*sizeof(struct node));
top->ptr = NULL;

top->info = data;
}
else
{

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


temp->ptr = top;

temp->info = data;
top = temp;
}
count++;
}

void display()
{
top1 = top;
if (top1 == NULL)
{
printf("Stack is empty");
return;

}
while (top1 != NULL)

23 | P a g e
{
printf("%d ", top1->info);

top1 = top1->ptr;
}
}

void pop()
{
top1 = top;
if (top1 == NULL)
{

printf("\n Error : Trying to pop from empty stack");


return;
}

else
top1 = top1->ptr;
printf("\n Popped value : %d", top->info);
free(top);

top = top1;
count--;
}
int topelement()
{

return(top->info);
}
void empty()
{
if (top == NULL)
printf("\n Stack is empty");
else

printf("\n Stack is not empty with %d elements", count);


}

24 | P a g e
void destroy()

{
top1 = top;
while (top1 != NULL)
{
top1 = top->ptr;
free(top);
top = top1;
top1 = top1->ptr;
}

free(top1);
top = NULL;
printf("\n All stack elements destroyed");
count = 0;

25 | P a g e
OUTPUT

RESULT

Thus the program for Linked List implementation of Stack was executed successfully.

26 | P a g e
Ex.No : 3b
LINKED LIST IMPLEMENTATION OF LINEAR QUEUE ADT
Date :

AIM
To write a C program to implement Queue ADT by using linked list

ALGORITHM

1. Start the program


2. Define a 'Node' structure with two members data and next.

3. Define two Node pointers 'front' and 'rear' and set both to NULL.

4. Implement the main method by displaying Menu of list of operations and make suitable v
function calls in the main method to perform user selected operation.

5. Inserting an element into the queue

• Create a newNode with given value and set 'newNode ^ next' to NULL.

• Check whether queue is Empty (rear == NULL)

• If it is Empty then, set front = newNode and rear = newNode.

• If it is Not Empty then, set rear ^ next = newNode and rear = newNode.

6. Deleting an Element from queue

• Check whether queue is Empty (front == NULL).

• If it is Empty, then display "Queue is Empty!!! Deletion is not possible!!!" and


terminate from the function

• If it is Not Empty then, define a Node pointer 'temp' and set it to 'front'.

• Then set 'front = front ^ next' and delete 'temp' (free(temp)).

7. display() - Displaying queue of elements

• Check whether queue is Empty (front == NULL).

• If it is Empty then, display 'Queue is Empty!!!' and terminate the function.

• If it is Not Empty then, define a Node pointer 'temp' and initialize with front.

27 | P a g e
• Display 'temp ^ data --->' and move it to the next node. Repeat the same until 'temp'
reaches to 'rear' (temp ^ next != NULL).

• Finally! Display 'temp ^ data ---> NULL'.

PROGRAM

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

{
int data;
struct node *next;
};

struct node *front = NULL;


struct node *rear = NULL;
void enqueue(int value) {
struct node *ptr;
ptr = (struct node *)malloc(sizeof(struct node));
ptr->data = value;
ptr->next = NULL;

if ((front == NULL) && (rear == NULL))


{
front = rear = ptr;
}
else

{
rear->next = ptr;
rear = ptr;
}
printf("Node is Inserted\n\n");
}

int dequeue()

28 | P a g e
{
if (front == NULL)
{

printf("\nUnderflow\n");
return -1;

}
else
{
struct node *temp = front;
int temp_data = front->data;
front = front->next;
free(temp);
return temp_data;
}
}
void display() {
struct node *temp;

if ((front == NULL) && (rear == NULL))


{
printf("\nQueue is Empty\n");
}
else

{
printf("The queue is \n");
temp = front;
while (temp)
{
printf("%d--->", temp->data);
temp = temp->next;
}
printf("NULL\n\n");

29 | P a g e
}
}
int main()

{
int choice, value;
printf("\nImplementation of Queue using Linked List\n");
while (choice != 4) {
printf("1.Enqueue\n2.Dequeue\n3.Display\n4.Exit\n");
printf("\nEnter your choice : ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("\nEnter the value to insert: ");

scanf("%d", &value);
enqueue(value);
break;
case 2:

printf("Popped element is :%d\n", dequeue());


break;
case 3:
display();
break;
case 4:
exit(0);
break;
default:

printf("\nWrong Choice\n");
}

}
return 0;
}

30 | P a g e
OUTPUT
Implementation of Queue using Linked List
1. Enqueue
2. Dequeue
3. Display
4. Exit

Enter your choice: 1


Enter the value to insert: 32
Node is Inserted
1. Enqueue
2. Dequeue
3. Display
4. Exit
Enter your choice: 3
The queue is
32--->NULL

1. Enqueue
2. Dequeue
3. Display
4. Exit
Enter your choice: 2
Popped element is: 32

RESULT
Thus the C program to implement Queue ADT by using linked list is executed successfully
and the output is verified.
31 | P a g e
Ex.No : 04 IMPLEMENTATION OF POLYNOMIAL MANIPULATION
Date : USING LINKED LIST

AIM
To write a program in C language for polynomial addition using Linked List

ALGORITHM

1. Start the process.

2. Create 2 Linked Lists for adding polynomial.

3. Give the coefficients and the powers for the two polynomials.

4. Check the power of the two polynomials

• If the powers are same, add its corresponding coefficients.


• Else, Store the highest power of the polynomial first.
• Then, Store the next power polynomial in the next nodes of the resultant polynomial.

5. Copy the remaining nodes of the polynomial to the resultant polynomial.

6. Display the resultant polynomial.

7. Stop the process.

PROGRAM

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

{
int coeff;
int pow;

struct Node* next;


};
void readPolynomial(struct Node** poly)
{
int coeff, exp, cont;
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));

32 | P a g e
*poly = temp;
do
{
printf("\n Coefficient: ");
scanf("%d", &coeff);
printf("\n Exponent: ");
scanf("%d", &exp);
temp->coeff = coeff;
temp->pow = exp;
temp-> next = NULL;
printf("\nHave more terms? 1 for y and 0 for no: ");
scanf("%d", &cont);
if(cont)

{
temp->next = (struct Node*)malloc(sizeof(struct Node));
temp = temp->next;
temp->next = NULL;

}
}while(cont);
}
void displayPolynomial(struct Node* poly)
{

printf("\nPolynomial expression is: ");


while(poly != NULL)
{

printf("%dX^%d", poly->coeff, poly->pow);


poly = poly->next;
if(poly != NULL)
printf("+");

}
}

33 | P a g e
void addPolynomials(struct Node** result, struct Node* first, struct Node* second)
{
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));

temp->next = NULL;
*result = temp;

while(first && second)


{
if(first->pow > second->pow)
{
temp->coeff = first->coeff;
temp->pow = first->pow;
first = first->next;

}
else if(first->pow < second->pow)

{
temp->coeff = second->coeff;
temp->pow = second->pow;
second = second->next;

}
else
{
temp->coeff = first->coeff + second->coeff;
temp->pow = first->pow;

first = first->next;
second = second->next;
}
if(first && second)
{

temp->next = (struct Node*)malloc(sizeof(struct Node));


temp = temp->next;
temp->next = NULL;

34 | P a g e
}
}
while(first || second)

temp->next = (struct Node*)malloc(sizeof(struct Node));


temp = temp->next;
temp->next = NULL;
if(first)
{
temp->coeff = first->coeff;
temp->pow = first->pow;
first = first->next;

}
else if(second)
{
temp->coeff = second->coeff;
temp->pow = second->pow;
second = second->next;

}
}
}
int main()
{
struct Node* first = NULL;
struct Node* second = NULL;
struct Node* result = NULL;

printf("\nEnter the corresponding data:-\n");


printf("\nFirst polynomial:\n");
readPolynomial(&first);
displayPolynomial(first);
printf("\nSecond polynomial:\n");

35 | P a g e
readPolynomial(&second);
displayPolynomial(second);
addPolynomials(&result, first, second);
displayPolynomial(result);
return 0;
}

36 | P a g e
OUTPUT

RESULT

Thus, the program for polynomial addition using linked list was written and executed
successfully

37 | P a g e
Ex.No : 5a
EVALUATING POSTFIX EXPRESSIONS
Date :

AIM
To write a program in C languages for evaluating postfix expressions

ALGORITHM

1. Add ) to postfix expression.


2. Read postfix expression Left to Right until ) encountered
3. If operand is encountered, push it onto Stack [End If]
4. If operator is encountered, Pop two elements
i) A -> Top element
ii) B-> Next to Top element
iii) Evaluate B operator A push B operator A onto Stack
5. Set result = pop
6. End

PROGRAM

#include <stdio.h>
#include <ctype.h>
#define MAXSTACK 100

#define POSTFIXSIZE 100


int stack[MAXSTACK];
int top = -1;
void push(int item)
{
if (top >= MAXSTACK - 1) {
printf("stack over flow");
return;

}
else
{

38 | P a g e
top = top + 1;
stack[top] = item;
}
}
int pop()

{
int item;
if (top < 0)
{
printf("stack under flow");

}
else
{

item = stack[top];
top = top - 1;
return item;
}
}
void EvalPostfix(char postfix[])
{

int i;
char ch;
int val;
int A, B;
for (i = 0; postfix[i] != ')'; i++) {
ch = postfix[i];

if (isdigit(ch)) {
push(ch - '0');
}
else if (ch == '+' || ch == '-' || ch == '*' || ch == '/')
{

39 | P a g e
A = pop();
B = pop();
switch (ch) /* ch is an operator */

{
case '*':
val = B * A;
break;
case '/':
val = B / A;
break;
case '+':
val = B + A;
break;
case '-':
val = B - A;

break;
}

push(val);
}
}
printf(" \n Result of expression evaluation : %d \n", pop());
}
int main()

{
int i;
char postfix[POSTFIXSIZE];
printf(" \nEnter postfix expression,\npress right parenthesis ')' for end expression : ");
for (i = 0; i <= POSTFIXSIZE - 1; i++)
{
scanf("%c", &postfix[i]);
if (postfix[i] == ')')

40 | P a g e
{
break;
}

EvalPostfix(postfix);
return 0;
}

41 | P a g e
OUTPUT

RESULT

Thus, the program for evaluating postfix expressions was written and executed successfully.

42 | P a g e
Ex.No : 5b
IMPLEMENTATION OF INFIX TO POSTFIX CONVERSION
Date :

AIM
To write a program for the conversion of infix to postfix using Stack in C language

ALGORITHM

1. Start the process.

2. Read the given infix expression into string called infix.

3. Read one character at a time and perform the following operations .

• If the read character is an operand, then add the operand to the postfix string.

• If the read character is not an operand, then check

• If the stack is not empty and precedence of the top of the stack operator is
higher than the read operator, then pop the operator from stack and add this
operator to the postfix string. Else push the operator onto stack.

4. Repeat STEP 2 till all characters are processed from the input string.

5. If stack is not empty, then pop the operator from stack and add this operator to the postfix
string.

6. Repeat STEP 4 till all the operators are popped from the stack.

7. Display the result of given infix expression or resultant postfix expression stored in a string
called postfix.

8. Stop the process

PROGRAM

#include<stdio.h>

#include<string.h>

#define operand(x) (x>='a' && x<='z' || x>='A' && x<='Z' || x>='0' && x<='9')

char infix[30],postfix[30],stack[30];

int top,i=0;

void init()

43 | P a g e
top=-1;

void push(char x)

stack[++top]=x;

char pop()

return(stack[top--]);

int isp(char x)

int y;

y=(x=='('?0:x=='^'?4:x=='*'?2:x=='/'?2:x=='+'?1:x=='-'?1:x==')'?6:-1);

return y;

int icp(char x)

int y;

y=(x=='('?4:x=='^'?4:x=='*'?2:x=='/'?2:x=='+'?1:x=='-'?1:x==')'?6:-1);

return y;

void infixtopostfix()

int j,n=0;

char x,y;

stack[++top]='\0';

for (j=0; (x=infix[i++])!='\0'; j--)

44 | P a g e
if (operand(x))

postfix[n++]=x;

else

if (x==')')

while ((y=pop())!='(')

postfix[n++]=y;

else

while (isp(stack[top])>=icp(x))

postfix[n++]=pop();

push(x);

while (top>=0)

postfix[n++]=pop();

int main()

init();

clrscr();

printf("\n Conversion of Infix to Postfix expression Using Stack\n");

printf("\nEnter an infix expression :\t");

scanf("%s",infix);

infixtopostfix();

printf("\nThe resulting postfix expression is : \t%s",postfix);

getch();

return 0;

45 | P a g e
OUTPUT

Conversion of Infix to Postfix expression Using Stack

Enter an infix expression : a*(b+c)

The resulting postfix expression is : abc+*

RESULT

Thus, the program for infix to postfix conversion was executed successfully

46 | P a g e
Ex.No : 6
IMPLEMENTATION OF BINARY SEARCH TREE
Date :

AIM

To write a C program to implement binary search tree


.
ALGORITHM
1. Start the program.
2. Get the input from the user.
3. Get the choice from the user.
4. If the choice is to create, then whether the tree is empty, if it is empty create a new node and
insert or else traverse the list to find the appropriate place for insertion.
5. If the choice is to delete , apply find and find the position of the element the element to be
deleted. Then delete the element.
7. Stop the execution

PROGRAM

#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *left;
struct node *right;

};
struct node *root = NULL;
struct node *create_node(int);
void insert(int);
struct node *delete (struct node *, int);

int search(int);

struct node *smallest_node(struct node *);


struct node *largest_node(struct node *);
int get_data();

47 | P a g e
int main()
{

int userChoice;

char userActive = 'Y';


int data;
struct node* result = NULL;
while (userActive == 'Y' || userActive == 'y')
{
printf("\n\n------- Binary Search Tree -------\n");

printf("\n1. Insert");
printf("\n2. Delete");
printf("\n3. Search");
printf("\n4. Get Larger Node Data");
printf("\n5. Get smaller Node data");
printf("\n6. Exit");
printf("\n\nEnter Your Choice: ");
scanf("%d", &userChoice);
printf("\n");
switch(userChoice)

{
case 1:

data = get_data();
insert(data);
break;
case 2:
data = get_data();
root = delete(root, data);
break;

case 3:
data = get_data();

48 | P a g e
if (search(data) == 1)
{
printf("\nData was found!\n");

}
else
{
printf("\nData does not found!\n");

}
break;
case 4:
result = largest_node(root);
if (result != NULL)
{

printf("\nLargest Data: %d\n", result->data);


}
break;
case 5:

result = smallest_node(root);
if (result != NULL)
{
printf("\nSmallest Data: %d\n", result->data);
}

break;
case 6:
printf("\n\nProgram was terminated\n");
break;
default:
printf("\n\tInvalid Choice\n");
break;

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

49 | P a g e
fflush(stdin);
scanf(" %C", &userActive);
}

return 0;
}
struct node *create_node(int data)
{

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


if (new_node == NULL)
{

printf("\nMemory for new node can't be allocated");


return NULL;
}

new_node->data = data;
new_node->left = NULL;
new_node->right = NULL;
return new_node;
}
void insert(int data)
{
struct node *new_node = create_node(data);
if (new_node != NULL)
{
if (root == NULL)
{

root = new_node;
printf("\n* node having data %d was inserted\n", data);
return;
}

struct node *temp = root;


struct node *prev = NULL;

50 | P a g e
while (temp != NULL)
{

prev = temp;
if (data > temp->data)
{
temp = temp->right;

}
else
{
temp = temp->left;
}
}
if (data > prev->data)

{
prev->right = new_node;
}
else
{
prev->left = new_node;

}
printf("\n data %d was inserted\n", data);

}
}
struct node *delete (struct node *root, int key)

{
if (root == NULL)
{
return root;
}
if (key < root->data)

51 | P a g e
{
root->left = delete (root->left, key);
}

else if (key > root->data)


{
root->right = delete (root->right, key);
}

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

{
struct node *temp = root->left;
free(root);
return temp;
}
struct node *temp = smallest_node(root->right);
root->data = temp->data;
root->right = delete (root->right, temp->data);
}
return root;

}
int search(int key)
{
struct node *temp = root;

while (temp != NULL)

52 | P a g e
{
if (key == temp->data)
{

return 1;
}
else if (key > temp->data)
{

temp = temp->right;
}
else
{
temp = temp->left;
}
}

return 0;
}
struct node *smallest_node(struct node *root)
{
struct node *curr = root;

while (curr != NULL && curr->left != NULL)


{
curr = curr->left;
}
return curr;
}

struct node *largest_node(struct node *root)


{
struct node *curr = root;
while (curr != NULL && curr->right != NULL)
{
curr = curr->right;

53 | P a g e
}
return curr;
}

int get_data()
{
int data;
printf("\nEnter Data: ");
scanf("%d", &data);
return data;

54 | P a g e
OUTPUT

55 | P a g e
RESULT

Thus the C programs to implement Binary search tree was executed successfully and
output is verified.

56 | P a g e
Ex.No : 07
IMPLEMENTATION OF AVL TREE
Date :

AIM
To write a C program to implement AVL trees

ALGORITHM

1. Start the program


2. Compare newKey with rootKey of the current tree.
• If newKey < rootKey, call insertion algorithm on the left subtree of the current node
until the leaf node is reached.
• Else if newKey > rootKey, call insertion algorithm on the right subtree of current
node until the leaf node is reached.
• Else, return leafNode.

3. Compare leafKey obtained from the above steps with newKey:

• If newKey < leafKey, make newNode as the leftChild of leafNode.


• Else, make newNode as rightChild of leafNode.

4. If the nodes are unbalanced, then rebalance the node.

• If balanceFactor > 1, it means the height of the left subtree is greater than that of the
right subtree. So, do a right rotation or left-right rotation
• If newNodeKey < leftChildKey do right rotation.
• Else, do left-right rotation

5. If balanceFactor < -1, it means the height of the right subtree is greater than that of the
left subtree. So, do right rotation or right-left rotation

• If newNodeKey > rightChildKey do left rotation.


• Else, do right-left rotation

6. Stop the program.

57 | P a g e
PROGRAM
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *left, *right;
int ht;

} node;
node *insert(node *, int);
node *Delete(node *, int);
void preorder(node *);
void inorder(node *);
int height(node *);
node *rotateright(node *);
node *rotateleft(node *);
node *RR(node *);

node *LL(node *);


node *LR(node *);
node *RL(node *);
int BF(node *);
int main() {

node *root = NULL;


int x, n, i, op;
do {
printf("\n1)Create:");
printf("\n2)Insert:");
printf("\n3)Delete:");
printf("\n4)Print:");

printf("\n5)Quit:");

58 | P a g e
printf("\n\nEnter Your Choice:");
scanf("%d", &op);
switch (op) {
case 1:
printf("\nEnter no. of elements:");
scanf("%d", &n);
printf("\nEnter tree data:");
root = NULL;
for (i = 0; i < n; i++) {
scanf("%d", &x);
root = insert(root, x);
}
break;
case 2:

printf("\nEnter a data:");
scanf("%d", &x);
root = insert(root, x);
break;
case 3:

printf("\nEnter a data:");
scanf("%d", &x);
root = Delete(root, x);
break;
case 4:
printf("\nPreorder sequence:\n");
preorder(root);
printf("\n\nInorder sequence:\n");
inorder(root);

printf("\n");
break;
}

59 | P a g e
}
while (op != 5);

return 0;
}

node * insert(node *T, int x) {


if (T == NULL)
{

T = (node*) malloc(sizeof(node));
T->data = x;
T->left = NULL;
T->right = NULL;

} else if (x > T->data) // insert in right subtree


{

T->right = insert(T->right, x);


if (BF(T) == -2) {
if (x > T->right->data)
T = RR(T);
else
T = RL(T);

}
} else if (x < T->data) {
T->left = insert(T->left, x);
if (BF(T) == 2) {

if (x < T->left->data)
T = LL(T);
else
T = LR(T);
}
}
T->ht = height(T);
return (T);

60 | P a g e
}
node * Delete(node *T, int x) {

node * p;
if (T == NULL) {
return NULL;

} else
if (x > T->data) // insert in right subtree
{
T->right = Delete(T->right, x);
if (BF(T) == 2) {

if (BF(T->left) >= 0)
T = LL(T);
else
T = LR(T);
}
} else if (x < T->data) {

T->left = Delete(T->left, x);


if (BF(T) == -2)//Rebalance during windup
{

if (BF(T->right) <= 0)
T = RR(T);
else
T = RL(T);

}
} else {

if (T->right != NULL) { //delete its inordersuccesor


p = T->right;
while (p->left != NULL)
p = p->left;
T->data = p->data;
T->right = Delete(T->right, p->data);

61 | P a g e
if (BF(T) == 2)//Rebalance during windup
{
if (BF(T->left) >= 0)

T = LL(T);
else

T = LR(T);
}
} else
return (T->left);
}

T->ht = height(T);
return (T);
}

int height(node *T) {


int lh, rh;
if (T == NULL)
return (0);
if (T->left == NULL)
lh = 0;
else
lh = 1 + T->left->ht;
if (T->right == NULL)
rh = 0;

else
rh = 1 + T->right->ht;
if (lh > rh)

return (lh);
return (rh);
}

node * rotateright(node *x) {


node * y;

62 | P a g e
y = x->left;
x->left = y->right;

y->right = x;

x->ht = height(x);
y->ht = height(y);
return (y);
}
node * rotateleft(node *x) {
node * y;
y = x->right;

x->right = y->left;
y->left = x;
x->ht = height(x);
y->ht = height(y);
return (y);

}
node * RR(node *T) {
T = rotateleft(T);
return (T);
}

node * LL(node *T) {


T = rotateright(T);
return (T);

}
node * LR(node *T) {

T->left = rotateleft(T->left);
T = rotateright(T);
return (T);
}

node * RL(node *T) {


T->right = rotateright(T->right);

63 | P a g e
T = rotateleft(T);
return (T);
}
int BF(node *T) {
int lh, rh;

if (T == NULL)
return (0);

if (T->left == NULL)
lh = 0;
else
lh = 1 + T->left->ht;
if (T->right == NULL)
rh = 0;
else
rh = 1 + T->right->ht;

return (lh - rh);


}

void preorder(node *T) {


if (T != NULL) {
printf("%d(Bf=%d) ", T->data, BF(T));
preorder(T->left);
preorder(T->right);

}
}
void inorder(node *T) {
if (T != NULL) {
inorder(T->left);
printf("%d(Bf=%d) ", T->data, BF(T));
inorder(T->right);

}
}

64 | P a g e
OUTPUT

RESULT
Thus, the program for AVL tree was written and executed successfully.

65 | P a g e
Ex.No : 08
IMPLEMENTATION OF HEAPS USING PRIORITY QUEUES
Date :

AIM
To write a C program to implement heap data structure

ALGORITHM

1. Start the program


2. Initially, declare number of nodes in the heap’
3. By using while, create a menu for all operations of heaps
4. Perform all the operation and display the result
5. Stop the program

PROGRAM

#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#define MAX 10
int arr[MAX];
int i,n;
void insert(int num)
{
if(n<MAX)
{
arr[n]=num;
n++;
}
else
printf("\n Array is full");
}
void makeheap()
{
for(i=1;i<n;i++)
{

66 | P a g e
int val=arr[i];
int j=i;
int f=(j-1)/2;
while(j>0&&arr[f]<val)//creatinag a MAX heap
{
arr[j]=arr[f];
j=f;
f=(j-1)/2;
}
arr[j]=val;
}
}
void display()
{
printf("/n");
for(i=0;i<n;i++)
printf("%d",arr[i]);
}
int main()
{
insert(14);
insert(12);
insert(9);
insert(8);
insert(7);
insert(10);
insert(18);
printf("\n The Elements are .....");
display();
makeheap();
printf("\n Heapified");
display();
return 0;
}

67 | P a g e
OUTPUT

RESULT

Thus the C program to implement heap was executed successfully and output is
verified.

68 | P a g e
Ex.No : 09
IMPLEMENTATION OF DIJKSTRA’S ALGORITHM
Date :

AIM
To write a C program to implement Dijkstra’s Algorithm

ALGORITHM

1. Create cost matrix C[ ][ ] from adjacency matrix adj[ ][ ]. 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] is infinity.

2. Array visited[ ] is initialized to zero.

3. If the vertex 0 is the source vertex then visited[0] is marked as 1.

4. Create the distance matrix, by storing the cost of vertices from vertex no. 0 to n-1 from the
source vertex 0.

5. Initially, distance of source vertex is taken as 0. i.e. distance[0]=0;

6. Choose a vertex w, such that distance[w] is minimum and visited[w] is 0. Mark visited[w]
as 1.

7. Recalculate the shortest distance of remaining vertices from the source.

8. Only, the vertices not marked as 1 in array visited[ ] should be considered for recalculation
of distance. i.e. for each vertex v

69 | P a g e
PROGRAM

#include<stdio.h>

#include<conio.h>

#define INFINITY 9999

#define MAX 10

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

int main()

clrscr();

int G[MAX][MAX],i,j,n,u;

printf("Enter no. of vertices:");

scanf("%d",&n);

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

for(i=0;i<n;i++)

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

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

printf("\nEnter the starting node:");

scanf("%d",&u);

dijkstra(G,n,u);

getch();

return 0;

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;

70 | P a g e
for(i=0;i<n;i++)

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

if(G[i][j]==0)

cost[i][j]=INFINITY;

else

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

mindistance=distance[i];

nextnode=i;

71 | P a g e
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++;

for(i=0;i<n;i++)

if(i!=startnode)

printf("\nDistance of node%d=%d",i,distance[i]);

printf("\nPath=%d",i);

j=i;

do

j=pred[j];

printf("<-%d",j);

}while(j!=startnode);

72 | P a g e
OUTPUT

RESULT

Thus the C program to implement Dijkstra’s Algorithm was executed successfully and
output is verified.

73 | P a g e
Ex.No : 10
IMPLEMENTATION OF PRIM’S ALGORITHM
Date :

AIM
To write a C program to implement Prim’s Algorithm

ALGORITHM

1. Start the program

2. Create edge list of given graph, with their weights.


3. Select an edge with lowest weight and add it to skeleton and delete edge from edge list.
4. Add other edges. While adding an edge take care that the one end of the edge should always
be in the skeleton tree and its cost should be minimum.
5. Repeat step 4 until n-1 edges are added.
6. Stop the program

PROGRAM

#include<stdio.h>

#include<conio.h>

int n, cost[10][10];

void prim()

int i, j, startVertex, endVertex;

int k, nr[10], temp, minimumCost = 0, tree[10][3];

temp = cost[0][0];

for (i = 0; i < n; i++) {

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

if (temp > cost[i][j]) {

temp = cost[i][j];

startVertex = i;

74 | P a g e
endVertex = j;

tree[0][0] = startVertex;

tree[0][1] = endVertex;

tree[0][2] = temp;

minimumCost = temp;

for (i = 0; i < n; i++) {

if (cost[i][startVertex] < cost[i][endVertex])

nr[i] = startVertex;

else

nr[i] = endVertex;

nr[startVertex] = 100;

nr[endVertex] = 100;

temp = 99;

for (i = 1; i < n - 1; i++) {

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

if (nr[j] != 100 && cost[j][nr[j]] < temp) {

temp = cost[j][nr[j]];

tree[i][0] = k;

tree[i][1] = nr[k];

tree[i][2] = cost[k][nr[k]];

minimumCost = minimumCost + cost[k][nr[k]];

nr[k] = 100;

75 | P a g e
for (j = 0; j < n; j++) {

if (nr[j] != 100 && cost[j][nr[j]] > cost[j][k])

nr[j] = k;

temp = 99;

printf("\nThe min spanning tree is:- ");

for (i = 0; i < n - 1; i++) {

for (j = 0; j < 3; j++)

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

printf("\n");

printf("\nMin cost : %d", minimumCost);

void main() {

int i, j;

printf("\nEnter the no. of vertices :");

scanf("%d", &n);

printf("\nEnter the costs of edges in matrix form :");

for (i = 0; i < n; i++)

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

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

printf("\nThe matrix is : ");

for (i = 0; i < n; i++) {

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

printf("%d\t", cost[i][j]);

76 | P a g e
}

printf("\n");

prim();

getch();

OUTPUT

RESULT
Thus the C program to implement Prim’s Algorithm was executed successfully
and output is verified.

77 | P a g e
Ex.No : 11a
IMPLEMENTATION OF LINEAR SEARCH
Date :

AIM
To write a C program to perform Linear Search

ALGORITHM

1. Start the program.

2. Read the search element from the user


3. Compare, the search element with the first element in the list.
4. If both are matching, then display "Given element found!!!" and terminate the function
5. If both are not matching, then compare search element with the next element in the list.

6. Repeat steps 3 and 4 until the search element is compared with the last element in the list.
7. If the last element in the list is also doesn't match, then display "Element not
found!!!" and terminate the function

PROGRAM

#include <stdio.h>

int main()
{

int array[100], search, c, n;


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

printf("Enter %d integer\n", n);


for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter a number to search\n");
scanf("%d", &search);

for (c = 0; c < n; c++)


{
if (array[c] == search) /* If required element is found */

78 | P a g e
{
printf("%d is present at location %d.\n", search, c+1);

break;
}
}

if (c == n)
printf("%d isn't present in the array.\n", search);
return 0;
}

79 | P a g e
OUTPUT

RESULT
Thus the program to perform linear search operation was executed successfully.
.

80 | P a g e
Ex.No : 11b
IMPLEMENTATION OF BINARY SEARCH
Date :

AIM
To write a C program to perform Binary Search operation

ALGORITHM

1. Start the program.


2. Read the search element from the user

3. Find the middle element in the sorted list


4. Compare, the search element with the middle element in the sorted list.
5. If both are matching, then display "Given element found!!!" and terminate the function

6. If both are not matching, then check whether the search element is smaller or larger
than middle element.
7. If the search element is smaller than middle element, then repeat steps 2, 3, 4 and 5
for the left sublist of the middle element.
8. If the search element is larger than middle element, then repeat steps 2, 3, 4 and 5 for
the right sublist of the middle element.
9. Repeat the same process until we find the search element in the list or until sublist
contains only one element.
10. If that element also doesn't match with the search element, then display "Element not
found in the list!!!" and terminate the function.

PROGRAM

#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,n,item,flag=0,low,high,mid;

clrscr();
printf("Enter the size of an array: ");

81 | P a g e
scanf("%d",&n);
printf("Enter the elements in ascending order: ");

for(i=0;i<n;i++)
scanf("%d",&a[i]);

printf("Enter the number to be search: ");


scanf("%d",&item);
low=0,high=n-1;
while(low<=high)

{
mid=(low+high)/2;
if(item==a[mid])

{
flag=1;
break;

}
else if(item<a[mid])
high=mid-1;

else
low=mid+1;
}
if(flag==0)
printf("%d is not found",item);
else

printf("%d is at position %d",item,mid+1);


getch();
}

82 | P a g e
OUTPUT

RESULT
Thus the program to perform binary search operation was executed successfully.
.

83 | P a g e
Ex.No : 12a
IMPLEMENTATION OF INSERTION SORT
Date :

AIM
To write a C program to implement Insertion sort.

ALGORITHM

1. It is efficient for smaller data sets, but very inefficient for larger lists.

2. Insertion Sort is adaptive, that means it reduces its total number of steps if a
partially sorted array is provided as input, making it efficient.
3. It is better than Selection Sort and Bubble Sort algorithms.

4. Its space complexity is less. Like bubble Sort, insertion sort also requires a single
additional memory space.
5. It is a stable sorting technique, as it does not change the relative order of elements
which are equal

PROGRAM

#include<stdio.h>
#include<conio.h>
void main()

{
int A[10],n,i;

void Insert_sort(int A[10],int n);


clrscr();
printf("\n\t\t Insertion sort");

printf("\n how many element are there?");


scanf("%d",&n);
printf("\n enter the element\n");
for(i=0;i<=n-1;i++)
scanf("%d",&A[i]);
Insert_sort(A,n);

84 | P a g e
getch();
}
void Insert_sort(int A[10],int n)

int i,j,temp;
for(i=1;i<=n-1;i++)
{

temp=A[i];
j=i-1;
while((j>=0)&&(A[j]>temp))

{
A[j+1]=A[j];
j=j-1;
}
A[j+1]=temp;
}

printf("\n the sorted list of elements is. .. \n");


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

85 | P a g e
OUTPUT

RESULT
Thus the program to perform insertion sort operation was executed successfully.

86 | P a g e
Ex.No : 12b
IMPLEMENTATION OF SELECTION SORT
Date :

AIM
To write a C program to implement selection sort.

ALGORITHM

1. Starting from the first element, we search the smallest element in the array, and

replace it with the element in the first position.


2. Then move on to the second position, and look for smallest element present in the

subarray, starting from index 1, till the last index.


3. Replace the element at the second position in the original array, or we can say at

the first position in the subarray, with the second smallest element.
4. This is repeated, until the array is completely sorted.

PROGRAM

#include<stdio.h>
#include<conio.h>
int n;
void main()
{
int i,A[10];

void selection(int A[10]);


clrscr();
printf("\n\t\tselection sort\n");
printf("\nhow many element are there?");
scanf("%d",&n);
printf("\nenter the element\n");
for(i=0;i<n-1;i++)
scanf("%d",&A[i]);
selection(A);

87 | P a g e
getch();
}
void selection(int A[10])

int i,j,Min,temp;
for(i=0;i<=n-2;i++)
{

Min=i;
for(j=i+1;j<=n-1;j++)
{

if(A[j]<A[Min])
Min=j;
}

temp=A[i];
A[i]=A[Min];
A[Min]=temp;

}
printf("\n the sorted list is. .. \n");
for(i=0;i<n;i++)
printf("%d",A[i]);
}

88 | P a g e
OUTPUT

RESULT
Thus the program to perform selection sort operation was executed successfully.

89 | P a g e
Ex.No : 13
IMPLEMENTATION OF MERGE SORT
Date :

AIM
To write a C program to implement merge sort.

ALGORITHM

1. Read the elements into the array.

2. Divide the input array into two parts in the middle. Call it as left part and right part.

3. Sort each of them separately.

4. The above process is continued for all the elements in the array.

5. Merge the two sorted parts

PROGRAM

#include<stdio.h>

void mergesort(int a[],int i,int j);

void merge(int a[],int i1,int j1,int i2,int j2);

int main()

int a[30],n,i;

printf("Enter no of elements:");

scanf("%d",&n);

printf("Enter array elements:");

for(i=0;i<n;i++)

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

mergesort(a,0,n-1);

printf("\nSorted array is :");

for(i=0;i<n;i++)

printf("%d ",a[i]);

90 | P a g e
return 0;

void mergesort(int a[],int i,int j)

int mid;

if(i<j)

mid=(i+j)/2;

mergesort(a,i,mid); //left recursion

mergesort(a,mid+1,j); //right recursion

merge(a,i,mid,mid+1,j); //merging of two sorted sub-arrays

void merge(int a[],int i1,int j1,int i2,int j2)

int temp[50]; //array used for merging

int i,j,k;

i=i1; //beginning of the first list

j=i2; //beginning of the second list

k=0;

while(i<=j1 && j<=j2) //while elements in both lists

if(a[i]<a[j])

temp[k++]=a[i++];

else

temp[k++]=a[j++];

while(i<=j1) //copy remaining elements of the first list

91 | P a g e
temp[k++]=a[i++];

while(j<=j2) //copy remaining elements of the second list

temp[k++]=a[j++];

//Transfer elements from temp[] back to a[]

for(i=i1,j=0;i<=j2;i++,j++)

a[i]=temp[j];

92 | P a g e
OUTPUT

RESULT:

Thus the above c program for sorting numbers using Merge sort was executed and the
output is verified successfully.

93 | P a g e
Ex.No : 14
IMPLEMENTATION OF OPEN ADDRESSING
Date :

AIM
To write a C program to implement open addressing linear probing and Quadratic
probing

ALGORITHM

1. Start the program.

2. Declare the variables.


3. An element is converted into an integer by using a hash function. This element can be used
as an index to store the original element, which falls into the hash table.

4. The element is stored in the hash table where it can be quickly retrieved using hashed
key. hash = hashfunc(key), index = hash % array_size

PROGRAM

#include <stdio.h>
#include <conio.h>
int tsize;
int hasht(int key)
{
int i ;

i = key%tsize ;
return i;
}
int rehashl(int key)
{
int i ;

i = (key+1)%tsize ;
return i ;
}

94 | P a g e
int rehashq(int key, int j)
{
int i ;

i = (key+(j*j))%tsize ;
return i;

}
void main()
{
int key,arr[20],hash[20],i,n,s,op,j,k ;
printf ("Enter the size of the hash table: ");

scanf ("%d",&tsize);

printf ("\nEnter the number of elements: ");


scanf ("%d",&n);
for (i=0;i<tsize;i++)
hash[i]=-1 ;
printf ("Enter Elements: ");
for (i=0;i<n;i++)
{
scanf("%d",&arr[i]);

}
do
{

printf("\n\n1.Linear Probing\n2.Quadratic Probing \n3.Exit \nEnter your option: ");


scanf("%d",&op);
switch(op)
{
case 1:
for (i=0;i<tsize;i++)
hash[i]=-1 ;
for(k=0;k<n;k++)

95 | P a g e
key=arr[k] ;
i = hasht(key);

while (hash[i]!=-1)
{
i = rehashl(i);

}
hash[i]=key ;
}
printf("\nThe elements in the array are: ");
for (i=0;i<tsize;i++)
{
printf("\n Element at position %d: %d",i,hash[i]);
}

break ;
case 2:
for (i=0;i<tsize;i++)
hash[i]=-1 ;
for(k=0;k<n;k++)
{

j=1;
key=arr[k] ;
i = hasht(key);
while (hash[i]!=-1)

{
i = rehashq(i,j);
j++ ;

}
hash[i]=key ;

}
printf("\nThe elements in the array are: ");
for (i=0;i<tsize;i++)

96 | P a g e
{
printf("\n Element at position %d: %d",i,hash[i]);
}

break ;
}
}while(op!=3);
getch() ;
}

97 | P a g e
OUTPUT

RESULT:

Thus the above c program for implementing linear and Quadratic probing was executed
successfully.

98 | P a g e

You might also like