Download as pdf or txt
Download as pdf or txt
You are on page 1of 41

Data Structures

Lab record suggestive format

B. Tech (IT) II year 1st semester

st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
Index

Program 1 - Binary search 3


Program 2 - Stack 6
Program 3 - Circular queue 12
Program 4 - Infix to Postfix 16
Program 5 - Postfix evaluation 19
Program 6 - Deque 21
Program 7 - Addition of polynomials using linked lists 26
Program 8 - Quick sort 30
Program 9 - Merge sort 33
Program 10 - Binary search tree and Tree traversals 37

st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
Program 1 - Binary search

I Aim

Write a C program for sorting a list using Bubble sort and then apply binary search.

II Theory

Bubble sort

1. Bubble sort is an algorithm that compares the adjacent elements and swaps their positions if they are
not in the intended order. The order can be ascending or descending.
2. Starting from the first index, the first and the second elements are compared. If the first element is
greater than the second element, they are swapped. Next, the second and the third elements are
compared and are swapped if they are not in order. The process is continued until the last element
3. The same process is applied for the remaining iterations. In each iteration, the comparison takes
place up to the last unsorted element. After each iteration, the largest element among the unsorted
elements is placed at the end.
4. The array is sorted when all the unsorted elements are placed at their correct positions.
2
5. The asymptotic time complexity of bubble sort is O(n )

Binary search

1. Binary search is a searching algorithm for finding an element's position in a sorted array.
2. Binary search can be implemented only on a sorted list of items. If the elements are not sorted
already, they need to be sorted first.
3. In this approach, the element is always searched in the middle of a portion of an array and half of the
elements are ignored after every comparison. The sorted array is searched by repeatedly dividing
the search interval in half.
4. The process begins with an interval covering the whole array. If the value of the search key is less
than the item in the middle of the interval, the interval is narrowed to the lower half. Otherwise it is
narrowed it to the upper half. The process is repeated until the value is found or the interval is
empty
5. The asymptotic time complexity of bubble sort is O(log n)

III Algorithm

// algorithm for bubble sort


bubbleSort(array)
for i <- 1 to indexOfLastUnsortedElement-1
if leftElement > rightElement
swap leftElement and rightElement
end bubbleSort

// algorithm for binary search


binarySearch(arr, x, low, high)
if low > high
return False

st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
else
mid = (low + high) / 2
if x == arr[mid]
return mid
else if x < data[mid] // x is on the right side
return binarySearch(arr, x, mid + 1, high)
else // x is on the right side
return binarySearch(arr, x, low, mid - 1)

IV Code

// Binary search using bubble sort


#include <stdio.h>
#include <stdlib.h>
int binarySearch(int array[], int x, int low, int high) {
if (high >= low) {
int mid = low + (high - low) / 2;

// If found at mid, then return it


if (array[mid] == x)
return mid;

// Search the left half


if (array[mid] > x)
return binarySearch(array, x, low, mid - 1);

// Search the right half


return binarySearch(array, x, mid + 1, high);
}

return -1;
}

void bubble(int a[],int s)


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

st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
int main(void) {
int n,i,x,result;
int *numbers;

clrscr();
printf("enter numberof elements:\n");
scanf("%d", &n);

numbers = malloc(n * sizeof(*numbers));

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


{
printf("enter element %d:\n", i+1);
scanf("%d", &numbers[i]);
}

// sort the array using bubble sort


bubble(numbers,n);

printf("\n");
printf("enter element to be searched:\n");
scanf("%d", &x);

result = binarySearch(numbers, x, 0, n - 1);


if (result == -1)
printf("Not found");
else
printf("Element is found at index %d", result+1);

getch();
return 0;
}

V Output

Enter number of elements : 5


enter element 1: 54
enter element 2: 45
enter element 3: 79
enter element 4: 32
enter element 5: 6

Enter element to be searched: 32

Element is found at index 4

* * *

st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
Program 2 - Stack

I Aim

Write a C program to implement the operations on stacks.

II Theory

Stack

1. Stack is a linear data structure in which the insertion and deletion operations are performed at only
one end
2. The end from which the operations are performed is called "top".
3. The stack operates on principle called LIFO i.e. Last In First Out. This is because the last element to
go into the stack will be the first element to be popped
4. Stack can be implemented by using either an array or linked list

Operations on stack

1. There are two operations in stack – insertion and deletion


2. The insertion operation is termed as “push” and the deletion operation is termed as “pop”

Implementing stack using array

1. Implementation of stack using array is called bounded stack because it is upper bounded with some
maximum capacity
2. First, fixed amount of storage space for the elements is allocated by defining an array of the required
size
3. As the elements are pushed into stack, the elements are written to the array
4. If the elements are inserted continuously and maximum capacity is reached, error is reported

Implementing stack using linked list

1. First, a structure called “cell” is defined which has two members – an integer called “val” and a pointer
called “next” which points to another cell
2. A pointer called “head” is defined and set it to NULL
3. For push operation, the following steps are performed:
1. a new cell structure is created -cell *newCell = (cell*) malloc(sizeof(cell));
2. this cell has two members as defined by the structure – value field and next pointer
3. the value field is set toto the parameter obtained for the push function - newCell->val = s;
4. the next pointer of the new cell is made to point to head - newCell->next = head;
5. finally, “head” is madeto point to the new cell - head = newCell;

st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
III Algorithm

Stack using array

// push operation
begin
if top = n then stack full
top = top + 1
stack (top) : = item;
end

// pop operation
begin
if top = 0 then stack empty;
item := stack(top);
top = top - 1;
end;

Stack using linked list

// push operation
Step 1 - Create a newNode with given value.
Step 2 - Check whether stack is empty (top == NULL)
Step 3 - If it is empty, then set newNode → next = NULL.
Step 4 - If it is not empty, then set newNode → next = top.
Step 5 - finally, set top = newNode.

// pop operation
Step 1 - Check whether stack is empty (top == NULL).
Step 2 - If it is empty, then display "stack is empty! deletion is not possible!!!" and terminate the function
Step 3 - If it is not empty, then define a node pointer 'temp' and set it to 'top'.
Step 4 - Then set 'top = top → next'.
Step 5 - finally, delete 'temp'. (free(temp)).

// display operation
Step 1 - Check whether stack is empty (top == NULL).
Step 2 - If it is empty, then display 'stack is empty!!!' and terminate the function.
Step 3 - If it is not empty, then define a node pointer 'temp' and initialize with top.
Step 4 - Display 'temp → data --->' and move it to the next node. Repeat the same until temp reaches to the first node
in the stack. (temp → next != NULL).
Step 5 – finally, display temp.

IV Code

Stack using array

// implementing stack using array


#include<conio.h>
#define SIZE 10

void push(int);
void pop();
void display();
st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
int stack[SIZE], top = -1;

void main()
{
int value, choice;
clrscr();
while(1){
printf("\n\n***** MENU *****\n");
printf("1. Push\n2. Pop\n3. Display\n4. Exit");
printf("\nEnter your choice: \n");
scanf("%d", &choice);
switch(choice)
{
case 1: printf("Enter the value to be inserted: ");
scanf("%d",&value);
push(value);
break;
case 2: pop();
break;

case 3: display();
break;
case 4: exit(0);
default: printf("\nWrong selection!!! Try again!!!");
}
}
}

void push(int value)


{
if(top == SIZE-1)
printf("\nStack is Full!!! Insertion is not possible!!!");
else
{
top++;
stack[top] = value;
printf("\nInsertion success!!!");
}
}

void pop()
{
if(top == -1)
printf("\nStack is Empty!!! Deletion is not possible!!!");
else
{
printf("\nDeleted : %d", stack[top]);
top--;
}}

st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
void display()
{
if(top == -1)
printf("\nStack is Empty!!!");
else
{
int i;
printf("\nStack elements are:\n");
for(i=top; i>=0; i--)
printf("%d ", stack[i]);
}
}

Stack using linked list

// implementing stack using linked list


#include<stdlib.h>
#include<conio.h>

typedef struct cell {


int val;
struct cell *next;
}cell;

cell *head=NULL;
void push(int);
int pop();
void display();

void main()
{
int value, choice;
clrscr();
while(1){
printf("\n\n***** MENU *****\n");
printf("1. Push\n2. Pop\n3. Display\n4. Exit");
printf("\nEnter your choice: \n");
scanf("%d", &choice);
switch(choice)
{
case 1: printf("Enter the value to be inserted: ");
scanf("%d",&value);
push(value);
break;
case 2: pop();
break;

case 3: display();
break;
case 4: exit(0);
default: printf("\nWrong selection!!! Try again!!!");

st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
}
}
}

void push(int s)
{
cell *newCell = (cell*) malloc(sizeof(cell)); // Allocate memory to a node
newCell->val = s; // insert the item
newCell->next = head;
head = newCell; // move head to new node
printf("%d inserted", s);
}

int pop()
{
int top;
cell *old;

if (head==NULL)
printf("pop empty stack error \n");
top = head->val;
old =head;
head = head->next;
free(old);
printf("%d popped", top);
return top;
}

void display()
{
if(head == NULL)
printf("\nStack is Empty!!!\n");
else
{
cell *temp = (cell*) malloc(sizeof(cell));
temp=head;
while(temp->next != NULL)
{
printf("%d ", temp->val);
temp = temp -> next;
}
printf("%d", temp->val);
}
}

V Output

1. Push
2. Pop
3. Display
4. Exit
st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
Enter your choice: 1
Enter the value to be inserted: 76
76 inserted

1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 1
Enter the value to be inserted: 91
91 inserted

1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 1
Enter the value to be inserted: 32
32 inserted

1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 3
32 91 76

1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 2
32 popped

1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 3
91 76

* * *

st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
Program 3 - Circular queue

I Aim

Write a C program to implement the operations on circular queues.

II Theory

Circular Queue

1. A queue is a linear structure which follows a particular order in which the operations are performed. The
order is First In First Out (FIFO). For example, a queue of customers where the customer that came first
is served first such as ticket counters
2. Adding elements to a queue is called enqueue while removing elements from the queue is
called dequeue
3. For implementing queue, two pointers called "front" and "rear" are maintained. The "front" pointer
tracks the first element of the queue while the "rear" pointer tracks the last element of the queue
4. One disadvantage with regular queue implementation is that the check for whether the queue is full or
not is done by the condition whether the rear pointer is pointing to the last node. If yes, then we infer
that the queue is full
5. However even if there is vacant slot, we will not be able to insert new element. This is because
indexes 0 and 1 can only be used after the queue is reset when all the elements have been
dequeued. This is non-utilisation of available space. This problem can be addressed using circular
queue
6. Circular queue works by the process of circular increment i.e. when we try to increment the pointer
and we reach the end of the queue, we start from the beginning of the queue. Tthe last position is
connected to the first position in a circular queue that forms a circle. It is also known as a ring buffer
7. The circular increment is performed by modulo division with the queue size.
8. Circular queues are used in applications such as memory management, CPU scheduling and traffic
system.

III Algorithm

// enqueue operation

Step 1: if (rear+1)%max = front


report " overflow "
goto step 4
[end of if]

Step 2: if front = -1 and rear = -1


set front = rear = 0
else if rear = max - 1 and front ! = 0
set rear = 0
else
set rear = (rear + 1) % max
[end of if]

Step 3: set queue[rear] = val

Step 4: exit

st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
// dequeue operation

Step 1: if front = -1
report " underflow "
goto step 4
[end of if]

Step 2: set val = queue[front]

Step 3: if front = rear


Set front = rear = -1
else
if front = max -1
set front = 0
else
set front = front + 1
[end of if]
[end of if]

Step 4: exit

IV Code

// Circular Queue implementation in C


#include <stdio.h>
#define SIZE 5

int items[SIZE];
int front = -1, rear = -1;

// Check if the queue is full


int isFull() {
if ((front == rear + 1) || (front == 0 && rear == SIZE - 1)) return 1;
return 0;
}

// Check if the queue is empty


int isEmpty() {
if (front == -1) return 1;
return 0;
}

// Adding an element
void enQueue(int element) {
if (isFull())
printf("\n Queue is full!! \n");
else {
if (front == -1) front = 0;
rear = (rear + 1) % SIZE;
items[rear] = element;
printf("\n Inserted -> %d", element);
}
}

st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
// Removing an element
int deQueue() {
int element;
if (isEmpty()) {
printf("\n Queue is empty !! \n");
return (-1);
} else {
element = items[front];
if (front == rear) {
front = -1;
rear = -1;
}
// Queuehas only one element, so we reset the queue after dequeing it.
else {
front = (front + 1) % SIZE;
}
printf("\n Deleted element -> %d \n", element);
return (element);
}
}

// Display the queue


void display() {
int i;
if (isEmpty())
printf(" \n Empty Queue\n");
else {
printf("\n Front -> %d ", front);
printf("\n Items -> ");
for (i = front; i != rear; i = (i + 1) % SIZE) {
printf("%d ", items[i]);
}
printf("%d ", items[i]);
printf("\n Rear -> %d \n", rear);
}
}

int main() {

int choice,item;
clrscr();
while(1)
{
printf("\n\n1.Enqueue\n 2.Dequeue\n 3.Exit\n ");
printf("\nEnter your choice :\n");
scanf("%d",&choice);

switch(choice)
{
case 1:
printf("\nInput the element for adding in queue : ");
scanf("%d",&item);
enQueue(item);
st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
break;
case 2:
deQueue(item);
break;
case 3:
exit(1);
default:
printf("\nWrong choice\n");
printf("\nfront = %d, rear =%d\n", front , rear);
display(); }

V Output

1. enqueue
2. dequeue
3. exit

Enter your choice: 1


Input the element for adding in the queue: 12
Inserted – 12
Front – 0
Items - 12
Rear - 0

Enter your choice: 1


Input the element for adding in the queue: 87
Inserted – 87
Front – 0
Items – 12 87
Rear – 1

Enter your choice: 1


Input the element for adding in the queue: 23
Inserted – 23
Front – 0
Items – 12 87 23
Rear – 2

Enter your choice: 2


Deleted element – 12
Front – 1
Items – 87 23
Rear – 2

Enter your choice: 1


Input the element for adding in the queue: 90
Inserted – 90
Front – 1
Items – 12 87 23
Rear – 3

* * *
st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
Program 4 - Infix to Postfix

I Aim

Write a C program for converting a given infix expression to postfix form using stack

II Theory

1. Infix expression means that the expression is of the form “a op b” i.e. operator is in-between every
pair of operands. Example –> 3 + 5
2. Postfix expression means that the expression of the form “a b op” i.e. operator is followed for every
pair of operands. Example –> 3 5 +
3. Infix expressions are difficult for compilers to process them. Consider the infix expression (a + b * c
+ d). The compiler first scans the expression to evaluate the expression b * c, then again scan the
expression to add a to it. The result is then added to d after another scan
4. The repeated scanning makes it very in-efficient. It is better to convert the expression to postfix(or
prefix) form before evaluation
5. The corresponding expression in postfix form is (abc*+d+). This postfix expressions can be
evaluated easily using a stack

III Algorithm

1. scan the infix expression from left to right


2. if the scanned character is an operand, output it (operand means numbers, operator means symbols like +, -, *)
3. if the scanned character is an operator, we have two cases to consider:
- if the precedence of the scanned operator is greater than the precedence of the operator in the stack (or the stack is
empty or the stack contains a ‘(‘ ), push it
- else, pop all the operators from the stack which are greater than or equal to in precedence than that of the scanned
operator. After doing that, push the scanned operator to the stack. (if you encounter parenthesis while popping then
stop there and push the scanned operator in the stack.)
4. if the scanned character is an ‘(‘, push it to the stack
5. if the scanned character is an ‘)’, pop the stack and output it until a ‘(‘ is encountered, and discard both the
parenthesis
repeat steps 2-5 until infix expression is scanned.
print the output
pop and output from the stack until it is not empty

IV Code

// conversion of infix expression to postfix notation

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

char stack[100];
int top = -1;

st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
void push(char x)
{
stack[++top] = x;
}

char pop()
{
if(top == -1)
return -1;
else
return stack[top--];
}

int priority(char x)
{
if(x == '(')
return 0;
if(x == '+' || x == '-')
return 1;
if(x == '*' || x == '/')
return 2;
return 0;
}

int main()
{
char exp[100];
char *e, x;
clrscr();
printf("Enter the expression : ");
scanf("%s",exp);
printf("\n");
e = exp;

while(*e != '\0')
{
if(isalnum(*e))
printf("%c ",*e);
else if(*e == '(')
push(*e);
else if(*e == ')')
{
while((x = pop()) != '(')
printf("%c ", x);
}
else
{
while(priority(stack[top]) >= priority(*e))
printf("%c ",pop());
push(*e);
}
e++;
}
st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
printf("The postfix expression is”);

while(top != -1)
{
printf("%c ",pop());
}
getch();
return 0;
}

V Output

Enter the expression: 7^2*(25+10/5)-13


The postfix expression is : 7 2 ^ 25 10 5 / + * 13 -

* * *

st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
Program 5 - Postfix evaluation

I Aim

Write a C program for evaluating a given postfix expression using stack.

II Theory

1. The postfix notation is used to represent algebraic expressions


2. The expressions written in postfix form are evaluated faster compared to infix notation as
parenthesis are not required in postfix
3. After converting infix to postfix, postfix evaluation is required to evaluate the expression.
4. Postfix notation is also referred to as Reverse Polish notation.

III Algorithm

1. create a stack to store operands (or values).


2. scan the given expression and do following for every scanned element:
a) if the element is a number, push it into the stack
b) if the element is a operator, pop operands for the operator from stack. Evaluate the operator and push the result
back to the stack
3. when the expression is ended, the number in the stack is the final answer.

IV Code

// evaluation of postfix expression

#include<stdio.h>
int stack[20];
int top = -1;

void push(int x)
{
stack[++top] = x;
}

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

int main()
{
char exp[20];
char *e;
int n1,n2,n3,num;

clrscr();
printf("Enter the expression \n");
scanf("%s",exp);

st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
e = exp;
while(*e != '\0')
{
if(isdigit(*e))
{
num = *e - 48;
push(num);
}
else
{
n1 = pop();
n2 = pop();
switch(*e)
{
case '+':
{
n3 = n1 + n2;
break;
}
case '-':
{
n3 = n2 - n1;
break;
}
case '*':
{
n3 = n1 * n2;
break;
}
case '/':
{
n3 = n2 / n1;
break;
}
}
push(n3);
}
e++;
}
printf("\nThe result of the expression %s = %d\n\n",exp,pop());
getch();
return 0;
}

V Output

Enter the expression: 4 2 3 5 1 - + * +


The result of the expression is : 18

* * *

st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
Program 6 - Deque

I Aim

Write a C program for implementing the operations of a deque.

II Theory

1. “Double ended queue”, shortened as deque, is a generalized version of queue. It allows insert and
delete at both ends.
2. Since insertion and removal of elements can be performed from either from the front or rear, it does
not follow FIFO rule (First In First Out) of normal queues
3. There are four basic operations that are performed on a deque
a. insert_frontEnd (): adds an item at the front of deque
b. insert_rearEnd (): adds an item at the rear of deque
c. delete_frontEnd (): deletes an item from front of deque
d. delete_rearEnd (): deletes an item from rear of deque

III Algorithm

1. for insertion at front:


a. first check if the queue is full
b. if the queue is not full, and the queue is empty, set both front and rear to 0
c. check the position of “front”. If it is zero, re-initialise front to last index; if not, decrease front by 1
d. add the new element at the position of front.
2. for insertion at rear:
a. first check if the queue is full
b. if the queue is not full, and the queue is empty, set both front and rear to 0
c. If the deque is full, reinitialize rear to zero; if not, increase rear by 1
d. add the new element at the position of rear.
3. for deletion from front:
a. first check if the queue is empty
b. if it is not empty and the queue has only one element, set both front and rear to -1
c. else if front is at the end of the queue, go to the front i.e. set front to zero; if not increment front by 1.
4. for deletion from rear:
a. first check if the queue is empty
b. if it is not empty and the queue has only one element, set both front and rear to -1
c. if rear is at the front, go to front i.e. set rear to (size – 1). if not, decrement rear by 1.IV Code

st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
IV Code

// Implementation of deque

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

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

void insert_frontEnd(int item);


void insert_rearEnd(int item);
int delete_frontEnd();
int delete_rearEnd();
void display();
int isEmpty();
int isFull();

int main()
{
int choice,item;
while(1)
{
printf("\n\n1.Insert at the front end\n");
printf("2.Insert at the rear end\n");
printf("3.Delete from front end\n");
printf("4.Delete from rear end\n");
printf("5.Display\n");
printf("6.Quit\n");
printf("\nEnter your choice :\n");
scanf("%d",&choice);

switch(choice)
{
case 1:
printf("\nInput the element for adding in queue : ");
scanf("%d",&item);
insert_frontEnd(item);
break;
case 2:
printf("\nInput the element for adding in queue : ");
scanf("%d",&item);
insert_rearEnd(item);
break;
case 3:
printf("\nElement deleted from front end is : %d\n",delete_frontEnd());
break;
case 4:
printf("\nElement deleted from rear end is : %d\n",delete_rearEnd());
break;

st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
case 5:
display();
break;
case 6:
exit(1);
default:
printf("\nWrong choice\n");
}/*End of switch*/
printf("\nfront = %d, rear =%d\n", front , rear);
display();
}/*End of while*/
}/*End of main()*/

void insert_frontEnd(int item)


{
if( isFull() )
{
printf("\nQueue Overflow\n");
return;
}
if( front==-1 )/*If queue is initially empty*/
{
front=0;
rear=0;
}
else if(front==0)
front=MAX-1;
else
front=front-1;
deque_arr[front]=item ;
}/*End of insert_frontEnd()*/

void insert_rearEnd(int item)


{
if( isFull() )
{
printf("\nQueue Overflow\n");
return;
}
if(front==-1) /*if queue is initially empty*/
{
front=0;
rear=0;
}
else if(rear==MAX-1) /*rear is at last position of queue */
rear=0;
else
rear=rear+1;
deque_arr[rear]=item ;
}/*End of insert_rearEnd()*/

st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
int delete_frontEnd()
{
int item;
if( isEmpty() )
{
printf("\nQueue Underflow\n");
exit(1);
}
item=deque_arr[front];
if(front==rear) /*Queue has only one element */
{
front=-1;
rear=-1;
}
else
if(front==MAX-1)
front=0;
else
front=front+1;
return item;
}/*End of delete_frontEnd()*/

int delete_rearEnd()
{
int item;
if( isEmpty() )
{
printf("\nQueue Underflow\n");
exit(1); }
item=deque_arr[rear];

if(front==rear) /*queue has only one element*/


{
front=-1;
rear=-1;
}
else if(rear==0)
rear=MAX-1;
else
rear=rear-1;
return item;
}/*End of delete_rearEnd() */

int isFull()
{
if ( (front==0 && rear==MAX-1) || (front==rear+1) )
return 1;
else
return 0;
}/*End of isFull()*/

st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
int isEmpty()
{
if( front == -1)
return 1;

else
return 0;
}/*End of isEmpty()*/

V Output

1. insert at the front end


2. insert at the rear end
3. delete from front end
4. delete from rear end
5. display
6. quit

Enter your choice: 1


Input the element for adding in the queue: 45
front = 0, rear = 0
Queue elements: 45

Enter your choice: 2


Input the element for adding in the queue: 56
front = 0, rear = 1
Queue elements: 45 56

Enter your choice: 2


Input the element for adding in the queue: 21
front = 0, rear = 2
Queue elements: 45 56 21

Enter your choice: 3


Element deleted from front end is: 45
front = 1, rear = 2
Queue elements: 56 21

Enter your choice: 4


Element deleted from rear end is: 21
front = 1, rear = 1
Queue elements: 56

* * *

st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
Program 7 - Addition of polynomials using linked lists

I Aim

Write a C program for the representation of polynomials using linked list and for the addition of two such
polynomials.

II Theory

1. To add two polynomials, we have to add the coefficients which have same variable powers
2 1 0 1 0
2. For example, if the first input is 1st number = 5x + 4x + 2x and the second input is -5x - 5x then
2 1 0 3 2 0 1 0
the output should be 5x -1x -3x If the first input is 5x + 4x + 2x and the second input is 5x - 5x
3 2 1 0
then the output should be 5x + 4x + 5x - 3x
3. To implement this using linked list, we define a node structure to have three data members –
coefficient, power and a next pointer
4. For each term in the polynomial, we create a new node. The result will be stored in a new polynomial

III Algorithm

The polynomial addition is done by the following logic:

i. if power of first polynomial is greater then 2nd,we store the first as it is and move its pointer

ii. if power of second polynomial is greater then first, we store second as it is and move its pointer

iii. if power of both polynomial numbers is same then we add their coefficients

IV Code

// Polynomial addition using linked list

#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("\n enter coeff:");
scanf("%d",&node->coeff);
printf("\n enter power:");
scanf("%d",&node->pow);
node->next=(struct link*)malloc(sizeof(struct link));
node=node->next;

st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
node->next=NULL;
printf("\n continue(y/n):");
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)
{
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;
}
else
{
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;
}

st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
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;
}
}
main()
{
char ch;
do{
poly1=(struct link *)malloc(sizeof(struct link));
poly2=(struct link *)malloc(sizeof(struct link));
poly=(struct link *)malloc(sizeof(struct link));
printf("\nenter 1st number:");
create(poly1);
printf("\nenter 2nd number:");
create(poly2);
printf("\n1st Number:");
show(poly1);
printf("\n2nd Number:");
show(poly2);
polyadd(poly1,poly2,poly);
printf("\nAdded polynomial:");
show(poly);
printf("\n add two more numbers:");
ch=getch();
}
while(ch=='y' || ch=='Y');
}

V Output

Enter first number:


enter coefficient: 2
enter power: 2
continue: y
enter coefficient: 1
enter power: 1
continue: y
enter coefficient: 3
enter power: 3
continue: n

Enter second number:


enter coefficient: 3
enter power: 2
continue: y

st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
enter coefficient: 6
enter power: 1
continue: y
enter coefficient: 8
enter power: 3
continue: n

First number: 2x^2+1x^1+3x^3


Second number: 3x^2+6x^1+8x^3
Added polynomial: 5x^2+7x^1+11x^3

* * *

st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
Program 8 - Quick sort

I Aim

Write a C program for quick sort.

II Theory

1. Quicksort uses the technique of divide-and-conquer


2. The process is as follows:
a. Pick an arbitrary element of the array (the pivot)
b. Divide the array into two segments, the elements that are smaller than the pivot and the
elements that are greater, with the pivot in between (the partition phase)
c. Recursively sort the segments to the left and right of the pivot
3. The main idea is to find the “right” position for the pivot element P. After each “pass”, the pivot
element, P, should be “in place”. Eventually, the elements are sorted since each pass puts at least
one element (i.e., P) into its final position
4. There are different ways to select the pivot - first element, last element, median-of-three elements
(pick three elements, find the median of these elements and use that median as the pivot), random
element, etc.
5. In the best case, the pivot element will be the median value among the array values. This just means
that half the values will end up in the left partition and half the values will end up in the right partition.
This results in O(nlog(n)) best-case asymptotic complexity
6. In the worst case, we always pick either the smallest or largest element in the array so that one side
of the partition will be empty, and the other has all elements except for the pivot itself. So quicksort
2
has quadratic complexity in the worst case O(n )

III Algorithm

Step 1 - consider the last element of the list as pivot (i.e., element at last position in the list).
Step 2 – define two variables i and j. Set i and j to first and last elements of the list respectively
Step 3 - increment i until list[i] > pivot then stop
Step 4 - decrement j until list[j] < pivot then stop
Step 5 - if i < j then exchange list[i] and list[j]
Step 6 - repeat steps 3,4 & 5 until i > j
Step 7 - exchange the pivot element with list[j] element

IV Code

/* QuickSort */
#include<stdio.h>
#include<stdlib.h>

// helper function to swap two elements


void swap(int* a, int* b)

st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
{
int t = *a;
*a = *b;
*b = t;
}

/* This function takes last element as pivot, places


the pivot element at its correct position in sorted
array, and places all smaller (smaller than pivot)
to left of pivot and all greater elements to right
of pivot */
int partition (int arr[], int low, int high)
{
int pivot = arr[high]; // pivot
int i = (low - 1); // Index of smaller element
int j;

// put the elements smaller than pivot on the left


// and greater than pivot on the right of pivot

for (j = low; j <= high- 1; j++)


{
// If current element is smaller than the pivot
if (arr[j] < pivot)
{
i++; // increment index of smaller element
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}

/* The main function that implements QuickSort


arr[] --> Array to be sorted,
low --> Starting index,
high --> Ending index */
void quickSort(int arr[], int low, int high)
{
if (low < high)
{
/* pi is partitioning index, arr[p] is now
at right place */
int pi = partition(arr, low, high);

// Separately sort elements before


// partition and after partition
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}

st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}

// Driver program
int main()
{
int n,i,size;
int *arr;
clrscr();
printf("enter numberof elements:\n");
scanf("%d", &n);

arr = malloc(n * sizeof(*arr));

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


{
printf("enter element %d:\n", i+1);
scanf("%d", &arr[i]);
}

quickSort(arr, 0, n-1);
printf("Sorted array: \n");
printArray(arr, n);
getch();
return 0;
}

V Output

Enter number of elements: 5


enter element 1: 45
enter element 2: 56
enter element 3: 27
enter element 4: 73
enter element 5: 6

Sorted array: 6 27 45 56 73

* * *

st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
Program 9 - Merge sort

I Aim

Write a C program for Merge sort.

II Theory

1. Merge sort follows the approach of divide and conquer


2. Merge sort has two steps – first, the divide phase and second, the merge phase
3. In the divide phase, we split the data into two halves and then split each of those halves into two
more halves and so on
4. Divide logic:
a. If less than two elements, return a copy of the list (base case). This is the base case because
if the list has only 1 element, it is already sorted so we just return the list as the result
b. Sort the first half using merge sort. (recursive)
c. Sort the second half using merge sort. (recursive)
a. Merge (using the below merge procedure) the two sorted halves to obtain the final sorted
array.
5. In the merge phase, the two sorted lists from the below level are put in combined sorted order
6. Merge logic:
a. input: two lists “a” and “b”, already sorted
b. output: a new list “c” containing the elements of a and b merged together in sorted order.
c. create an empty list c, set index_a and index_b to 0
d. while index_a < length of a and index_b < length of b (so we need two trackers index_a and
index_b)
i. Add the smaller of a[index_a] and b[index_b] to “c”, and increment the index of the
list with the smaller element (so at any point of time, we move only one tracker)
e. if any elements are left over in a or b, add them to the end of c, in order
f. return c
7. Merge sort is an efficient sorting algorithm. In the worst case, merge sort requires O(n log 2n) time to
sort an array with n elements.

III Algorithm

MergeSort(A, p, r):
if p > r
return
q = (p+r)/2
mergeSort(A, p, q)
mergeSort(A, q+1, r)
merge(A, p, q, r)

st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
The merge function works as follows:
create copies of the subarrays L ← A[p..q] and M ← A[q+1..r].
create three pointers i, j and k
i maintains current index of L, starting at 1
j maintains current index of M, starting at 1
k maintains the current index of A[p..q], starting at p.
until we reach the end of either L or M, pick the larger among the elements from L and M and place them in the
correct position at A[p..q]
when we run out of elements in either L or M, pick up the remaining elements and put in A[p..q]

IV Code

// Merge sort

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

// Merge two subarrays L and M into arr


void merge(int arr[], int p, int q, int r) {

// Create L ← A[p..q] and M ← A[q+1..r]


int n1 = q - p + 1;
int n2 = r - q;
int *L, *M;
int i,j,k;

L = malloc(n1 * sizeof(arr[0]));
M = malloc(n2 * sizeof(arr[0]));

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


L[i] = arr[p + i];
for (j = 0; j < n2; j++)
M[j] = arr[q + 1 + j];

// Maintain current index of sub-arrays and main array

i = 0;
j = 0;
k = p;

// Until we reach either end of either L or M, pick larger among


// elements L and M and place them in the correct position at A[p..r]
while (i < n1 && j < n2) {
if (L[i] <= M[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = M[j];
j++;
}

st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
k++;
}

// When we run out of elements in either L or M,


// pick up the remaining elements and put in A[p..r]
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}

while (j < n2) {


arr[k] = M[j];
j++;
k++;
}
}

// Divide the array into two subarrays, sort them and merge them
void mergeSort(int arr[], int l, int r) {
if (l < r) {

// m is the point where the array is divided into two subarrays


int m = l + (r - l) / 2;

mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);

// Merge the sorted subarrays


merge(arr, l, m, r);
}
}

// Print the array


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

// Driver program
int main() {

int n,i,size;
int *arr;
clrscr();
printf("enter numberof elements:\n");
scanf("%d", &n);

arr = malloc(n * sizeof(*arr));

st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
for (i=0; i<n; i++)
{
printf("enter element %d:\n", i+1);
scanf("%d", &arr[i]);
}

mergeSort(arr, 0, n - 1);

printf("Sorted array: \n");


printArray(arr, n);

getch();
return 0;
}

V Output

Enter number of elements: 5


enter element 1: 34
enter element 2: 23
enter element 3: 57
enter element 4: 41
enter element 5: 3

Sorted array: 3 23 34 41 57

* * *

st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
Program 10 - Binary search tree and Tree traversals

I Aim

Write a C program to create a binary search tree and for implementing the in order, preorder, post order
traversal using recursion.

II Theory

Binary search tree

1. One of the disadvantages of using an array or linked list to store data is the time required to search
for an item. Since both arrays and linked lists are linear structures, the time required to search a
linear list is proportional to the size of the data set
2. A tree is a collection of nodes connected by directed (or undirected) edges. A tree is a nonlinear data
structure, compared to arrays, linked lists, stacks and queues which are linear data structures
3. A tree where each node can have no more than two children is called a binary tree i.e. a node can
have 0 or 1 or 2 child nodes –but no more than 2. It cannot have 3 or 4 or any other higher number of
child nodes
4. Binary search tree is also a binary tree – but there are additional properties
5. Properties of binary search tree:
a. The left subtree of a node contains only nodes with keys lesser than the node’s key
b. The right subtree of a node contains only nodes with keys greater than the node’s key
c. The left and right subtree each must also be a binary search tree
d. There must be no duplicate nodes
6. The advantage of this ordering property in binary search tree is that we can search for an element
very efficiently.

Tree traversals

1. Traversing a tree means visiting every node in the tree. Linear data structures like
arrays, stacks, queues, and linked list have only one way to read the data. But a hierarchical data
structure like a tree can be traversed in different ways
2. Depending on the order in which we visit the nodes, there can be three types of traversals
3. Inorder traversal:
a. first, visit all the nodes in the left subtree
b. then the root node
c. visit all the nodes in the right subtree
4. Preorder traversal:
a. first, visit the root node
b. visit all the nodes in the left subtree
c. visit all the nodes in the right subtree
5. Postorder traversal:

st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
a. first, visit all the nodes in the left subtree
b. visit all the nodes in the right subtree
c. visit the root node
6. Each of these traversals will visit every node of the binary search tree in a particular order.

III Algorithm

Inorder taversal

if (root != null)
{
inorder(rootleft)
print(rootdata)
inorder(rootright)
}

Preorder taversal

if (root != null)
{
print(rootdata)
preorder(rootleft)
preorder(rootright)
}

Postorder traversal

if (root != null)
{
postorder(rootleft)
postorder(rootright)
print(rootdata)
}

IV Code

// Binary Search Tree creation and tree traversals

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

typedef struct node {


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

// Create a node
node *newNode(int item) {
node *temp = (node *)malloc(sizeof(node));
temp->key = item;
temp->left = temp->right = NULL;

st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
return temp;
}

// Insert a node
node *insert(node *node, int key) {
// Return a new node if the tree is empty
if (node == NULL) return newNode(key);

// Traverse to the right place and insert the node


if (key < node->key)
node->left = insert(node->left, key);
else
node->right = insert(node->right, key);

return node;
}

// Inorder Traversal
void inorder(node *root) {

if (root != NULL) {

// Traverse left
inorder(root->left);

// Traverse root
printf("%d -> ", root->key);

// Traverse right
inorder(root->right);
}
}

// Preorder Traversal
void preorder(node *root) {

if (root != NULL) {

// Traverse root
printf("%d -> ", root->key);

// Traverse left
preorder(root->left);

// Traverse right
preorder(root->right);
}
}

// Postorder Traversal
void postorder(node *root) {

if (root != NULL) {
st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
// Traverse left
postorder(root->left);

// Traverse right
postorder(root->right);

// Traverse root
printf("%d -> ", root->key);

}
}

// Driver code
int main() {
node *root = NULL;

int value, choice;


clrscr();

root = insert(root, 38);


root = insert(root, 5);
root = insert(root, 45);
root = insert(root, 1);
root = insert(root, 9);
root = insert(root, 47);
root = insert(root, 8);
root = insert(root, 15);
root = insert(root, 46);
root = insert(root, 13);

printf("\n\n***** MENU *****\n");


printf("1. Inorder\n2. Preorder\n3. Postorder\n4. Exit");
printf("\nEnter your choice: \n");
scanf("%d",&choice);
printf("\Tree elements: \n – 38,5,45,1,9,47,8,15,46,13");

switch(choice){

case 1:
printf("Inorder traversal: ");
inorder(root);
break;
case 2:
printf("Preorder traversal: ");
preorder(root);
break;
case 3:
printf("Postorder traversal: ");
postorder(root);
break;
case 4: exit(0);
default: printf("\nWrong selection!!! Try again!!!");
st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
}

getch();
return 0;
}

V Output

Tree elements: 38,5,45,1,9,47,8,15,46,13


1. Inorder
2. Preorder
3. Postorder

Enter your choice: 1


Inorder traversal: 1 5 8 9 13 15 38 45 46 47
Enter your choice: 2
Preorder traversal: 38 5 1 9 8 15 13 45 47 46

Enter your choice: 3


Postorder traversal: 1 8 13 15 9 5 46 47 45 38

* * *

st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu

You might also like