KEMBAR78
DSA Lab Report | PDF | Algorithms And Data Structures | Computer Programming
0% found this document useful (0 votes)
257 views33 pages

DSA Lab Report

The document describes experiments on implementing array operations like traversal, search, insertion and deletion. It provides the theory and procedures for each operation and includes code to perform these array operations on a linear array through a menu driven program.

Uploaded by

Sudipta Mondol
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)
257 views33 pages

DSA Lab Report

The document describes experiments on implementing array operations like traversal, search, insertion and deletion. It provides the theory and procedures for each operation and includes code to perform these array operations on a linear array through a menu driven program.

Uploaded by

Sudipta Mondol
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/ 33

Experiment No.

01

Experiment Name: Implementing Array Traversal, Search, Insertion, and Deletion

Theory: A linear array is a list of a finite number n of homogeneous data elements (i.e., data elements of the
same type) such that:
(a) The elements of the array are referenced respectively by an index set consisting of n consecutive
numbers.
(b) The elements of the array are stored respectively successive memory locations.

Some array operations are stated below.


(a) Traversal. Processing each element in the list.
Procedure:
1. [Initialize counter] Set K := LB
2. Repeat Steps 3 and 4 while K ≤ UB
3. [Visit element] Apply PROCESS to LA[K]
4. [Increase counter] Set K := K + 1
[End of Step 2 loop]
5. Exit

(b) Search. Finding the location of the element with a given value or the record with a given key.
Procedure:
1. [Insert ITEM at the end of DATA] Set DATA[N + 1] := ITEM.
2. [Initialize counter] Set LOC := 1
3. [Search from ITEM]
Repeat while DATA[LOC] ≠ ITEM:
Set LOC := LOC + 1
[End of loop]
4. [Successful?] If LOCK = N + 1, then: Set LOC := 0
5. Exit

(c) Insertion. Adding a new element to the list.


Procedure:
1. [Initialize the counter] Set J := N
2. Repeat Steps 3 and 4 while J ≥ K
3. [Move Jth element downward] Set LA[J + 1] := LA[J]
4. [Decrease counter] Set J := J – 1
[End of Step 2 loop]
5. [Insert element] Set LA[K] := ITEM
6. [Reset N] Set N := N + 1
7. Exit

(d) Deletion. Removing an element from the list.


Procedure:
1. Set ITEM := LA[K]
2. Repeat for J = K to N – 1:
[Move J + 1st element upward] set LA[J] := LA[J + 1]
[End of loop]
3. [Reset the number N of elements in LA] Set N := N - 1
4. Exit
Code:
#include<stdio.h>
#include<stdlib.h>
void traverse(int,int[]);
void search(int,int[]);
void insertion(int*,int[],int);
void deletion(int*,int[]);
int main()
{
int n;
printf("Enter array size : ");
scanf("%d",&n);
int arr[n];

int length;
printf("Enter array element number :");
scanf("%d",&length);
arr[length];

for(int i = 0; i < length; i++)


{
printf("Enter index value of arr[%d] :",i);
scanf("%d",&arr[i]);
}
int choice;
do{
printf("Which Operation do you want to run? \n 1.Traverse\n
2.Search\n 3.Insertion\n 4.Deletion\n 5.Exit\n Enter:");

scanf("%d",&choice);

switch(choice)
{
case 1:
{
traverse(length, arr);
break;
}
case 2:
{
search(length, arr);
break;
}
case 3:
{
insertion(&length, arr,n);
break;
}
case 4:
{
deletion(&length, arr);
break;
}
case 5 :
{
exit(0);
}
default :
{
printf("Enter correct value \n");
}
}
}while(1);

return 0;
}

void traverse(int length, int arr[length])


{
printf("Array Traversal:");
for(int i = 0; i < length ; i++)
{
printf("%d ",arr[i]);
}
printf("\n");
}

void search(int length, int arr[length])


{
int search,found;
printf("Enter Data to search:");
scanf("%d",&search);

for(int i = 0 ; i < length ; i++ )


{
if(search == arr[i])
{
found = i;
}
}
if(search == arr[found])
{
printf("Array Element Found!\nElement index is arr[%d]\n
",found);
}
else
{
printf("Element Not Found!");
}
}
void insertion(int *length,int arr[],int n)
{
int ins;
printf("Enter Data to insert:");
scanf("%d",&ins);

int index;
printf("Enter the index to insert data:");
scanf("%d",&index);

for(int i = *length - 1; i >= index ; i--)


{
arr[i+1] = arr[i ];
}
(*length)++;
arr[index] = ins;
if(*length > n)
{
printf("Overflow!\n");
}
else
{
traverse(*length,arr);
}
}
void deletion(int *length, int arr[])
{
int index;
printf("Enter index value to delete data:");
scanf("%d",&index);

int temp;
temp = arr[index];

for(int i = index ; i <= *length - 1 ; i++)


{
arr[i] = arr[i+1];
}
(*length)-- ;
if(*length < 0)
{
printf("Underflow!\n");
}
else if(*length == 0)
{
printf("Array is empty!\n");
}
else
{
traverse(*length,arr);
}
}
Experiment No. 02

Experiment Name: To implement code for Stack push and pop.

Theory: A stack is a list of elements in which an element may be inserted or deleted only at one end, called
the top of the stack. This means, in particular, that elements are removed from a stack in the reverse order
of that in which they were inserted into the stack. Stacks are also called last-in first-out lists (LIFO). Special
terminology is used for two basic operations associated with stacks:
(a) “Push” is the term used to insert an element into a stack.
(b) “Pop” is the term used to delete an element from a stack.

Stack operations are stated below.


(a) Push
Procedure:
1. [Stack already filled?]
If TOP = MAXSTK, then: Print: OVERFLOW, and Return
2. Set TOP := TOP + 1. [Increase TOP by 1]
3. Set STACK[TOP] := ITEM [Insert ITEM in new TOP position]
4. Return
(b) Pop
Procedure:
1. [Stack has an item to be removed?]
If TOP = 2, then: Print: UNDERFLOW, and Return
2. Set ITEM := STACK[TOP] [Assigns TOP element to ITEM]
3. Set TOP := TOP – 1 [Decreases TOP by 1]
4. Return

Code:

#include<stdio.h>
void push(int,int[]);
void pop(int,int[]);
void traverse(int,int[]);
int top = -1;
int main()
{
int length;
printf("Enter array size:");
scanf("%d",&length);
int arr[length];

int choice;
do
{
printf("Enter Your choice : \n 1.PUSH \n 2.POP \n
3.EXIT \n Enter :");

scanf("%d",&choice);
switch(choice)
{
case 1:
push(length,arr);
break;
case 2:
pop(length,arr);
break;
}
}
while(choice >= 0 && choice <= 2);
return 0;
}

void traverse(int length, int arr[])


{
printf("Array Elements are:");
for(int i = 0; i <= length ; i++)
{
printf("%d ",arr[i]);
}
printf("\n");
}

void push(int length, int arr[])


{
if(top == length - 1)
{
printf("Stack overFlow! \n");
}
else
{
top = top + 1;
int data;
printf("Enter new data:");
scanf("%d",&data);
arr[top] = data;
traverse(top,arr);
}
}
void pop(int length,int arr[])
{
if(top == -1)
{
printf("Stack Underflow! \n");
}
else if(top == 0){
top = top - 1;
printf("Stack is Empty!\n");
}
else
{
top = top - 1;
traverse(top,arr);
}
}
Experiment No. 03

Experiment Name: To implement code for Queue- Enqueue and Dequeue.

Theory: A queue is a linear list of elements in which deletions can take place only at one end, called the
front, and insertions can take place only at the other end, called the rear. The terms “front” and “rear” are
used in describing a linear list only when it is implemented as a queue.
Queues are also called first-in first-out (FIFO) lists, since the first element in a queue will be the first element
out of the queue. In other words, the order in which elements enter a queue is the order in which they
leave.

Some terminologies of queue are described below.


(a) Dequeue. A deque (pronounced either “deck” or dequeuer”) is a linear list in which elements can be
added or removed at either end but not in the middle. The term dequeue is a contraction of the
name double-ended queue. In general dequeue removes an element from the back of the queue.
Procedure:
1. [Queue already filled?]
If FRONT = 1 and REAR = N, or if FRONT = REAR + 1, then:
Write: OVERFLOW, and Return
2. [Find new value or REAR]
If FRONT := NULL, then: [Queue initially empty]
Set FRONT := 1 and READ := 1
Else if REAR = N, then:
Set REAR := 1
Else:
Set REAR := REAR + 1
[End of If structure]
3. Set QUEUE[REAR] := ITEM
4. Return.
(b) Enqueue. Adds an item from the back of the queue.
Procedure:
1. [Queue already empty?]
If FRONT := NULL, then: Write: UNDERFLOW, and Return
2. Set ITEM := QUEUE[FRONT]
3. [Find new value of FRONT]
If FRONT = REAR, then: [Queue has only one element to start]
Set FRONT := NULL and REAR := NULL
Else if FRONT = N, then:
Set FRONT := 1
Else:
Set FRONT := FRONT + 1
[End of If structure]
4. Return
Code:

#include<stdio.h>
void enqueue(int,int[]);
void dequeue(int,int[]);
void traverse(int,int[]);
int front = -1;
int rear = -1;
int main()
{
int length;
printf("Enter array Size :");
scanf("%d",&length);
int arr[length];
int option;
do
{
printf("Which Operation do you want to run?\n 1.Enqueue\n
2.Dequeue\n 3.Exit \n Enter:");

scanf("%d",&option);
switch(option)
{
case 1:
enqueue(length,arr);
break;
case 2:
dequeue(length,arr);
break;
}
}
while(option > 0 && option < 3);

}
void traverse(int length,int arr[length])
{
printf("Array Elements are : ");
for(int i = 0 ; i <= length ; i++)
{
printf("%d ",arr[i]);
}
printf("\n");
}

void enqueue(int length, int arr[length])


{
if(rear == length - 1)
{
printf("Queue overFlow!\n");
}
else
{
rear = rear + 1;
int data;
printf("Enter a data :");
scanf("%d",&data);
arr[rear] = data;
traverse(rear,arr);
}
}

void dequeue(int length,int arr[length])


{
front = front + 1;
if(front == rear)
{
front = -1 ;
rear = -1;
printf("Queue is Empty!\n");
}
else if(rear == -1)
{
front = -1;
printf("Queue underFlow!\n");
}
else
{
int temp = arr[front];
printf("Array Elements are : ");
for(int i = front + 1; i <= rear ; i++ )
{
printf("%d ",arr[i]);
}
printf("\n");
}
}
Input & Output:
Experiment No. 04

Experiment Name: To implement the following fundamental operations of Linked List: Creation, Insertion.

Theory: A linked list, or one-way list, is a linear collection of data elements, called nodes, where the linear
order is given by means of pointers. That is, each node is divided into two parts: the first part contains the
information of the element, and the second part, called the link field or nextpointer field, contains the
address of the next node in the list.

Some list operations are stated below.


(a) Traversal. Processing each element in the list.
Procedure:
1. Set PTR := START. [Initializes pointer PTR]
2. Repeat Steps 3 and 4 while PTR ≠ NULL
3. Apply PROCESS TO INFO[PTR]
4. Set PTR := LINK[PTR]. [PTR now points to the next node]
[End of Step 2 loop]
5. Exit.
(b) Searching. If we apply linear search, there will be no difference between a sorted list and unsorted
list.
Procedure:
1. Set PTR := START
2. Repeat Step 3 while PTR ≠ NULL:
3. If ITEM = INFO[PTR], then:
4. Set LOC := PTR, AND Exit.
Else:
Set PTR := LINK[PTR]
[End of If structure]
[End of step 2 loop]
5. [Search is unsuccessful] Set LOC := NULL
6. Exit.
(c) Insertion. Algorithms which insert nodes into linked lists come up in various situations. We can
consider three situations. The first one inserts a node at the beginning of the list, the second one
inserts a node after the node with a giver location, and the third one inserts a node into a sorted list.
Procedure.
1. [OVERFLOW?] If AVAIL = NULL, then: Write: OVERFLOW, and EXIT.
2. [Remove first node from AVAIL list]
Set NEW := AVAIL and AVAIL := LINK[AVAIL]
3. Set INFO[NEW] := ITEM [Copies new data into new node]
4. Set LINK[NEW] := START [New node now points to original first node]
5. Set START := NEW [Changes START so it points to the new node]
6. Exit.
(d) Deletion. Algorithms which delete nodes from linked lists come up in various situations. Let’s
consider two of them. The first one deletes the node following a given node, and the second one
deletes the node with a given ITEM of information.
Procedure.
1. If LOCP = NULL, then:
Set START := LINK[START]. [Deletes first node]
Else:
Set LINK[LOCP] := LINK[LOC]. [Deletes node N]
[End of If structure]
2. [Return deleted node to the AVAIL list]
Set LINK[LOC] := AVAIL and AVAIL := LOC
3. Exit.
Code:
#include<stdio.h>
#include<stdlib.h>

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

struct node *insertatposition(struct node *head)


{
printf("Linked list insertion : \n");

int data;
printf("Enter data : ");
scanf("%d",&data);

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


p -> data = data;
p -> next = NULL;

if(head == NULL)
{
head = p;
}
else
{
int position;
printf("Enter position : ");
scanf("%d",&position);

struct node *ptr = head;

if(position == 1)
{
p -> next = ptr;
head = p;
}
else
{
for(int i = 1 ; i < position - 1 ; i++)
{
ptr = ptr -> next;
}

p -> next = ptr -> next;


ptr -> next = p;
}
}

return head;
};
struct node *deletefromposition(struct node *head)
{
printf("Linked List deletion : \n");
int position;
printf("Enter position : ");
scanf("%d",&position);

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

struct node *ptr = head;


struct node *q = head -> next;

if(position == 1)
{
p = ptr;
return q;
}
else
{
for(int i = 1; i < position - 1; i++)
{
ptr = ptr -> next;
q = q -> next ;
}
p = ptr -> next;
ptr -> next = q -> next;
return head;
}
free(p);

};

void traverse(struct node *head)


{
printf("Linked List Elements are : ");
while(head != NULL)
{
printf("%d ",head -> data);
head = head -> next;
}
printf("\n");
}

int main()
{
printf("Linked List : \n");

struct node *head;


head = (struct node *)malloc(sizeof(struct node));
head = NULL;
int option;
do
{
printf("Which operation do you want to run? \n 1.Insertion \n
2.Deletion \n 3.Exit \n Enter : ");
scanf("%d",&option);

switch(option)
{
case 1 :
{
head = insertatposition(head);
traverse(head);
break;
}
case 2 :
{
if(head != NULL)
{
head = deletefromposition(head);
if(head != NULL)
{
traverse(head);
}
else
{
printf("Empty NODE!\n");
}
break;
}
else
{
printf("Underflow!\n");
break;
}
}
case 3:
{
exit(0);
}
default :
{
printf("Please ! Enter correct option value!!!\n");
}
}
}
while(1);

return 0;
}
Input & Output:
Experiment No. 05

Experiment Name: To implement a code for the Selection Sort technique.

Theory: Let A be a list of n elements A1, A2, …, An in memory. Sorting A refers to the operation of rearranging
the contents of A so that are increasing in order (numerically or lexicographically), that is, so that
A1 ≤ A2 ≤ A3 … ≤ An
Since A has n elements, there are n! ways that the contents can appear in A. These ways correspond
precisely to the n! permutation of 1, 2, …, n. Accordingly, each sorting algorithm must take care of these n!
possibilities.

Selection sort: One of the simplest sorting algorithms works as follows: first find the smallest element in the
array and exchange it with the element in the first position, then find the second smallest element and
exchange it with the element in the second position, and continue in this way until the entire array is sorted.
The method is called selection sort because it works by repeatedly “selecting” the smallest remaining
element.
Procedure:
1. Set MIN := A[K] and LOC := K [Initializes pointers]
2. Repeat for J = K + 1, K + 2, …, N:
If MIN > A[J], then: Set MIN := A[J] and LOC := A[J] and LOC := J
[End of loop]
3. Return.

Code:
#include <stdio.h>

void selection_sort(int arr[], int n) {


int min, temp;
for (int i = 0; i < n-1; i++) {
min = i;
for (int j = i+1; j < n; j++) {
if (arr[j] < arr[min]) {
min = j;
}
}
if (min != i) {
temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
}
}

int main() {
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);

int arr[n];
printf("Enter the elements: ");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Unsorted data: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");

selection_sort(arr, n);

printf("Sorted data: ");


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

return 0;
}

Input & Output:


Experiment No. 06

Experiment Name: To implement a code for the Insertion Sort technique.

Insertion sort: An algorithm almost as simple as selection sort but perhaps more flexible is insertion sort.
This is the method people often use to sort bridge hands: Consider the elements one at a time, inserting
each in tis proper place among those already considered (keeping them sorted). The element being
considered is inserted merely by moving larger elements one position to the right and then inserting the
elements into the vacated position.
Procedure:
1. Set A[0] := -∞ [Initializes sentinel elements]
2. Repeat Steps 3 to 5 for K = 2, 3, …, N:
3. Set TEMP := A[K] and PTR := K – 1.
4. Repeat while TEMP < A[PTR]:
(a) Set A[PTR + 1] := A[PTR] [Moves elements forward]
(b) Set PTR := PTR – 1
[End of loop]
5. Set A[PTR + 1] := TEMP. [Insert element in proper place]
[End of loop]
6. Return.

Code:

#include <stdio.h>

// Function to perform insertion sort on an array


void insertionSort(int arr[], int n) {
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;

// Move elements of arr[0..i-1], that are greater than key,


// to one position ahead of their current position
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}

// 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");
}

int main() {
int n, i;

// Taking the number of elements from the user


printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];

// Taking the array elements from the user


printf("Enter the elements: \n");
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

printf("Original array: \n");


printArray(arr, n);

insertionSort(arr, n);

printf("Sorted array: \n");


printArray(arr, n);

return 0;
}

Input & Output:


Experiment No. 07

Experiment Name: To implement a code for the Merge Sort technique.

Marge sort: Merge sort is an efficient, general-purpose, and comparison-based sorting algorithm. Most
implementations produce a stable sort, which means that the relative order of equal elements is the same in
the input and output. Merge sort is a divide-and-conquer algorithm that was invented by John von
Neumann.
Procedure:
MERGEPASS(A, N, L, B) MERGESORT(A, N)

1. Set Q := INT(N / (2 * L), S := 2 * L * Q and R 1. Set L := 1 [Initializes the number of


:= N – S. elements in the subarrays]
2. [Merge the q pairs of subarrays] 2. Repeat Steps 3 to 6 while L < N:
Repeat for J = 1, 2, …, Q: 3. Call MERGEPASS(A, N, L, B)
(a) Set LB := 1 + (2 * J – 2) * L. [Finds
4. Call MERGEPASS(B, N, 2 * L, A)
lower bound of first array]
(b) Call MERGE(A, L, LB, A, L, LB + L, B,
5. Set L := 4 * L
LB) [End of Step 2 loop]
[End of loop] 6. Exit.
3. [Only one subarray left?]
If R ≤ L, then:
Repeat for J = 1, 2, …, R:
Set B(S + J) := A(S + J)
[End of loop]
Else:
Call MERGE(A, L, S + 1, A, R, L + S + 1, B, S +
1)
[End of If structure]
4. Return.

Code:
#include <stdio.h>

// Function to merge two subarrays of arr[]


void merge(int arr[], int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;

// Create temporary arrays


int leftArr[n1], rightArr[n2];

// Copy data to temporary arrays


for (int i = 0; i < n1; i++)
leftArr[i] = arr[left + i];
for (int j = 0; j < n2; j++)
rightArr[j] = arr[mid + 1 + j];

/* Merge the temporary arrays back into arr[left..right]*/


int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (leftArr[i] <= rightArr[j]) {
arr[k] = leftArr[i];
i++;
} else {
arr[k] = rightArr[j];
j++;
}
k++;
}

/* Copy the remaining elements of leftArr[] if there are any */


while (i < n1) {
arr[k] = leftArr[i];
i++;
k++;
}

/* Copy the remaining elements of rightArr[] if there are any */


while (j < n2) {
arr[k] = rightArr[j];
j++;
k++;
}
}

/* Function to implement Merge Sort recursively */


void mergeSort(int arr[], int left, int right) {
if (left < right) {
// Find the middle point
int mid = left + (right - left) / 2;

// Sort first and second halves


mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);

// Merge the sorted halves


merge(arr, left, mid, right);
}
}

/* Function to print an array */


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

int main() {
int n;

printf("Enter the number of elements: ");


scanf("%d", &n);

int arr[n];

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


for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

printf("Unsorted array: \n");


printArray(arr, n);

mergeSort(arr, 0, n - 1);

printf("Sorted array: \n");


printArray(arr, n);
return 0;
}

Input & Output:


Experiment No. 08

Experiment Name: To implement a code for Bubble Sort technique.

Bubble sort: Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly
steps through the input list element by element, comparing the current element with the one after it,
swapping their values if needed. These passes through the list are repeated until no swaps have to be
performed during a pass, meaning that the list has become fully sorted. The algorithm, which is a
comparison sort, is named for the way the larger elements "bubble" up to the top of the list.

Procedure:
1. begin BubbleSort(arr)

2. for all array elements

3. if arr[i] > arr[i+1]

4. swap(arr[i], arr[i+1])

5. end if

6. end for

7. return arr

8. end BubbleSort

Code:

#include<stdio.h>
void bubbleSort(int,int[]);
void traverse(int,int[]);
int main()
{
int length;
printf("Enter array size : ");
scanf("%d",&length);

int arr[length];
for(int i = 0; i < length; i++)
{
printf("Enter value of index arr[%d] : ",i);
scanf("%d",&arr[i]);
}
traverse(length,arr);
bubbleSort(length,arr);
}

void traverse(int length,int arr[length])


{
printf("Array Elements are :");
for(int i = 0; i < length ; i++)
{
printf("%d ",arr[i]);
}
printf("\n");
}
void bubbleSort(int length,int arr[length])
{
for(int i = 0; i < length ; i++)
{
int swap = 0;
for(int j = 0; j < length - 1; j++)
{
if(arr[j] > arr[j+1])
{
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
swap = 1;
}
}
if(swap == 0)
{
break;
}
}
printf("After Bubble Sort :\n");
traverse(length,arr);
}

Input & Output:


Experiment No. 09
Experiment Name: To implement a code for Binary search .

Theory: Binary search also known as half-interval search, logarithmic search or binary chop, is a search
algorithm that finds the position of a target value within a stored array. Binary search compares the target
value to the middle element of the array. If they are not equal, the half in which the target cannot lie is
eliminated and the search continues on the remaining half, again taking the middle element to compare to the
target value, and repeating this until the target value is found. If the search ends with the remaining half being
empty, the target is not in the array.

Procedure:
1. Set L to 0 and R to n – 1
2. If L > R, the search terminates as unsuccessful
3. Set m (the position of the middle element) to the floor of (L + R) / 2, which is the greatest integer less
than or equal to (L + R) / 2.
4. If Am < T, set L to m + 1 and go to step 2
5. If Am > T, set R to m – 1 and go to step 2
6. Now Am = T, the search is done
7. Return m

Code:

#include<stdio.h>
#include<math.h>
void bubbleSort(int,int[]);
void traverse(int,int[]);
void arrayInput(int,int[]);
void binarySearch(int,int,int[]);
int main()
{
int length;
printf("Enter the array size : ");
scanf("%d",&length);
int arr[length];
arrayInput(length,arr);
bubbleSort(length,arr);

int src;
printf("Enter data to search : ");
scanf("%d",&src);

binarySearch(length,src,arr);
}

void arrayInput(int length,int arr[length]){


printf("Array Input : \n");
for(int i = 0 ; i < length ; i++){
printf("Enter array value of index arr[%d] : ",i);
scanf("%d",&arr[i]);
}
}

void bubbleSort(int length,int arr[length])


{
for(int i = 0; i < length ; i++)
{
int swap = 0;
for(int j = 0; j < length - 1 ; j++)
{
if(arr[j] > arr[j+1])
{
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
swap = 1;
}
}
if(swap == 0)
{
break;
}
}
printf("In Shorted Form : \n");
traverse(length,arr);
}

void traverse(int length,int arr[length]){


printf("Array Elements are : ");
for(int i = 0; i < length; i++){
printf("%d ",arr[i]);
}
printf("\n");
}

void binarySearch(int length,int src,int arr[length]){


int low = 0;
int high = length - 1;
int mid;
while(high >= low){
mid = floor((high + low)/2) ;
if(arr[mid] == src){
printf("Array element found!\n Array Index is arr[%d]",mid);
break;
}
else if(arr[mid] > src){
high = mid - 1 ;

}
else{
low = mid + 1;

}
}
if(arr[mid] != src){
printf("Array element not found!");
}
}
Input and Output:
Experiment No. 10
Experiment Name: To implement a code for a Binary Search Tree.

Theory: A Binary Search Tree is a data structure used in computer science for organizing and storing data in a
sorted manner. Each node in a Binary Search Tree has at most two children, a left child and a right child, with
the left child containing values less than the parent node and the right child containing values greater than the
parent node. This hierarchical structure allows for efficient searching, insertion, and deletion operations on the
data stored in the tree.

Procedure:
1. Search (root, item)
2. if (item = root → data) or (root = NULL)
3. return root
4. else if (item < root → data)
5. return Search(root → left, item)
6. else
7. return Search(root → right, item)
8. END if
9. END

Code:

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

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

struct node *creatNode(int data)


{
struct node *p = (struct node *)malloc(sizeof(struct node));
p -> data = data;
p -> left = NULL;
p -> right = NULL;
return p;
};

struct node *insert(struct node *root,int data)


{

if(root == NULL)
{
root = creatNode(data);
}
else if(root -> data >= data)
{
root -> left = insert(root -> left,data);
}
else
{
root -> right = insert(root -> right,data);
}
return root;
};

void inOrder(struct node *root)


{
if(root != NULL)
{
inOrder(root -> left);
printf("%d ",root -> data);
inOrder(root -> right);
}
};

void search(struct node *root,int key)


{
if(root == NULL)
{
printf("Not Found!!!\n");
}
else if(root -> data == key)
{
printf("Found!!!\n");
}
else if(root -> data >= key)
{
search(root -> left, key);
}
else
{
search(root -> right, key);
}
};

int main()
{
printf("BINARY SEARCH TREE\n");
struct node *root = (struct node *)malloc(sizeof(struct node));
root = NULL;
int option;
do
{
printf("\n Which operation do you want to Run? \n 1.Insertion \n
2.Searching \n 3.Exit \n Enter : ");

scanf("%d",&option);
switch(option)
{
case 1 :
{
int data;
printf("Enter data : ");
scanf("%d",&data);
root = insert(root,data);
inOrder(root);
break;
}
case 2 :
{
int key;
printf("Enter a Value to search : ");
scanf("%d",&key);
search(root,key);
inOrder(root);
break;
}
case 3 :
{
exit(0);
}
default :
{
printf("Enter correct Option!!!");
break;
}
}
}
while(1);
return 0;
}
Input and Output:

You might also like