Professional Documents
Culture Documents
Record - Suggestive Format
Record - Suggestive Format
st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
Index
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
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
return -1;
}
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);
printf("\n");
printf("enter element to be searched:\n");
scanf("%d", &x);
getch();
return 0;
}
V Output
* * *
st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
Program 2 - Stack
I Aim
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. 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
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
// 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;
// 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
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 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]);
}
}
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
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 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 4: exit
IV Code
int items[SIZE];
int front = -1, rear = -1;
// 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);
}
}
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
* * *
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
IV Code
#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
* * *
st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
Program 5 - Postfix evaluation
I Aim
II Theory
III Algorithm
IV Code
#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
* * *
st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
Program 6 - Deque
I Aim
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
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;
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()*/
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];
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
* * *
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
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
#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
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
* * *
st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
Program 8 - Quick sort
I Aim
II Theory
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>
st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
{
int t = *a;
*a = *b;
*b = t;
}
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);
quickSort(arr, 0, n-1);
printf("Sorted array: \n");
printArray(arr, n);
getch();
return 0;
}
V Output
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
II Theory
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>
L = malloc(n1 * sizeof(arr[0]));
M = malloc(n2 * sizeof(arr[0]));
i = 0;
j = 0;
k = p;
st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu
k++;
}
// Divide the array into two subarrays, sort them and merge them
void mergeSort(int arr[], int l, int r) {
if (l < r) {
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
// Driver program
int main() {
int n,i,size;
int *arr;
clrscr();
printf("enter numberof elements:\n");
scanf("%d", &n);
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);
getch();
return 0;
}
V Output
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
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(rootleft)
print(rootdata)
inorder(rootright)
}
Preorder taversal
if (root != null)
{
print(rootdata)
preorder(rootleft)
preorder(rootright)
}
Postorder traversal
if (root != null)
{
postorder(rootleft)
postorder(rootright)
print(rootdata)
}
IV Code
#include <stdio.h>
#include <stdlib.h>
// 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);
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;
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
* * *
st
Data Structures lab record suggestive format – B.Tech (IT) II year 1 semester – Sandeep Maddu