Professional Documents
Culture Documents
Lab Assignment 2: 1. Write Algorithm and Javascript Code For Linear Search
Lab Assignment 2: 1. Write Algorithm and Javascript Code For Linear Search
Lab Assignment 2: 1. Write Algorithm and Javascript Code For Linear Search
ALGORITHM
Step 1- Start from the leftmost element of arr[] and one by one compare x with
each element of arr[].
Step 2- If x matches with an element, return the index.
Step 3-If x doesn’t match with any of elements, return -1.
PROGRAM
<script>
// Javascript code to linearly search x in arr[]. If x
function search(arr, n, x)
{
let i;
for (i = 0; i < n; i++)
if (arr[i] == x)
return i;
return -1;
}
// Driver code
let arr = [ 2, 3, 4, 10, 40 ];
let x = 3;
let n = arr.length;
// Function call
let result = search(arr, n, x);
(result == -1)
? document.write("Element is not present in array")
: document.write("Element is present at index " + result);
</script>
OUTPUT:
2. For every element, traverse the array from start to that index and
find the maximum height (a) and traverse the array from the current
index to end and find the maximum height (b).
PROGRAM
<script>
// Javascript implementation of the approach
// Function to return the maximum
// water that can be stored
function maxWater(arr, n)
{
// To store the maximum water
// that can be stored
let res = 0;
let arr = [ 0, 1, 0, 2, 1, 0,
1, 3, 2, 1, 2, 1 ];
let n = arr.length;
document.write(maxWater(arr,n));
</script>
OUTPUT:
3. Write algorithm and JavaScript code for maximum sub array.
ALGORITHM
Step 1-Initialize: max_so_far = INT_MIN
max_ending_here = 0
step 2-The simple idea of algorithm is to look for all positive contiguous
segments of the array (max_ending_here is used for this).
Step 3- Keep track of maximum sum contiguous segment among all positive
segments (max_so_far is used for this).
Step 4 - Each time we get a positive-sum compare it with max_so_far and
update max_so_far if it is greater than max_so_far.
PROGRAM
<script>
// JavaScript program to find maximum
// subarray
// Function to find the maximum
// subarray
function maxSubArraySum(a, size)
{
var maxint = Math.pow(2, 53)
var max_so_far = -maxint - 1
var max_ending_here = 0
for (var i = 0; i < size; i++)
{
max_ending_here = max_ending_here + a[i]
if (max_so_far < max_ending_here)
max_so_far = max_ending_hereif (max_ending_here < 0)
max_ending_here = 0
}
return max_so_far
}
// Driver code
var a = [ -2, -3, 4, -1, -2, 1, 5, -3 ]
document.write("Maximum Array is ", maxSubArraySum(a,a.length))
</script>
OUTPUT
PROGRAM:
<script>
function climbStairs(N)
{ if(N<
2)
return 1
else
return climbStairs(N-1)+climbStairs(N-2)
}
N=prompt("Enter no. of staircase steps")
document.write("<br>No.of ways to climb staircases are :"+climbStairs(N))
</script>
OUTPUT: