Dsa Lab Assignment: 1. Write A Program To Implement Binary Search Tree

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

DSA LAB ASSIGNMENT

1. Write a program to implement binary search tree.

ALGORITHM
Binary-Search (A, x, l, r ) //initial call parameters are Binary-Search(A,l,n,x)
Step 1 :- if l>r then
Step 2 :- return -1; //Not found
Step 3 :- end if
Step 4 :- m=[(l+r)/2];
Step 5 :- if A[m] =x then
Step 6 :- return m
Step 7:- else if x<A[m] then
Step 8 :- return Binary-Search(A, x, l, m-1)
Step 9 :- else
Step 10 :- return Binary-Search(A, x, m+1, r)
Step 11 :- end if

PROGRAM
<script>
// Edit your script here
function binarySearch(arr,l,r,x)
{
if(r>=l)
{
mid= l + Math.floor((r-l)/2);
if(arr[mid]==x)
return mid;
if(arr[mid]>x)
return binarySearch(arr,l,mid-1,x);
return binarySearch(arr,mid+1,r,x);
}
return-1;
}
arr =[2,3,4,10,40];
x=prompt("Enter number to search");
n=arr.length
result =binarySearch(arr,0,n-1,x);
(result == -1)
document.write("Element is not present in array");
document.write("Element is present at index" +result);
</script>
<!-- edit your html here -->

OUTPUT
2. WRITE THE PROGRAM TO IMPLEMENT TOWER OF HANOI

ALGORITHM
Step 1 :- START
Step 2 :- Procedure Hanoi(disk, source, dest, aux)
Step 3 :- if disk ==1, then
Step 4 :- move disk from source to dest
Step 5 :- else
Step 6 :- Hanoi(disk-1, source, aux, dest) //Step 1
Step 7 :- move disk from source to dest // Step 2
Step 8 :- Hanoi(disk-1, aux, dest, source) //Step 3
Step 9 :- END IF
Step 10 :- END PROCEDURE
Step 11 :- STOP

PROGRAM
<script>
// Edit your script here
function towerOfHanoi(n, from_rod, to_rod, aux_rod)
{
if(n==1)
{
document.write("Move disk 1 from rod" + from_rod+ "to rod" +
to_rod+ "<br/>");
return;
}
towerOfHanoi(n-1, from_rod, aux_rod, to_rod);
document.write("Move disk" +n + "from rod" + from_rod +
"to rod" + to_rod+"<br/>");
towerOfHanoi(n-1, aux_rod, to_rod, from_rod);
}
var n=4;
towerOfHanoi(n, 'A', 'C', 'B'); //A,B,C are names of rods
</script>
<!-- edit your html here -->

OUTPUT

You might also like