Computer Science, asked by Jacob1095, 11 months ago

Given an unsorted array of n elements find if the element k is present in the array or not javascript

Answers

Answered by Anonymous
0

Given an unsorted array of n elements, find if the element k is present in the array or not.

Complete the findNumber function in the editor below. It has 2 parameters:

An array of integers, arr, denoting the elements in the array.

An integer, k, denoting the element to be searched in the array.

The function must return a string “YES” or “NO” denoting if the element is present in the array or not.

I have seen this type of problem before in a lecture. It is most efficient to use a binary search algorithm after sorting the array.

Binary search works like so: A sorted array is like a phone book. I want to look up the number for something like “Gary’s Guitar Lessons.” I flip to the middle, and the page has the number for “Ma and Pa’s Diner.” I throw out the bottom half because “Gary’s” would be in between the beginning and the middle. Then, I would repeat the process of (1) going to the middle and checking, (2) throwing out a half, and (3) checking the middle of the other half. Eventually, I will find it or determine it’s missing from the phone book.

Binary search is better than linear search in terms of time complexity because the amount of data gone through goes down by a half, as opposed to 1 item less. (assuming both are given a sorted array as an argument)

I implemented a binary search quickly based on my pseudocode knowledge…

Answered by AskewTronics
0

Below are the program for the above question:

Explanation:

Program:

var arr = new Array();//array declaration.

var size=prompt("Enter the size of the array"); //take the value for the size of the array.

for(var i=0;i<size;i++)//for loop for input the element for the array.

{

  var item=prompt("Enter the value for array"); //take the value for the array.

  arr.push(item);

}

var item=prompt("enter the element to be searched in the array");

var c=0;

for(var i=0;i<size;i++) //for loop to search the element of the array.

if(item==arr[i])  

{

  alert("item is matched");

  break;

  c=1;

}

if(c==0)  

alert("Item is not present in the array");

Output:

  • If the user inputs 5 for the size and 1,2,3,4,5 for the array and 6 for search, then it prints the element is not found.
  • If the user inputs 5 for the size and 1,2,3,4,5 for the array and 4 for search, then it prints the element is found.

Code Explanation:

  • The above code is in javascript which take the first size for the array, then it take th value for the array and assign the value on the array.
  • Then it use the for loop to search the items k from the arry and message is printed by the program.

Learn More:

  • Java script: https://brainly.in/question/11364798
Similar questions