In: Computer Science
problem 1 Write a function to search an item named searchkey in an array of 20 elements. Assumed the array has all integer value and also the search item is an integer.
problem 2 Now consider the array is sorted. Modify the above script (from question 1) in a way so that dont have to search the item in every position of the array( not looking 20 times considering worst case scenario).
thanks in advance
1)
NOTE: I only initialized four array elements but you can initialize as many as you want just change loop and add elements in the array.
<!DOCTYPE html>
<html>
<title>Web Page Design</title>
<head>
<script>
function search(){
var a =[12,31,123,45];
var searchkey=31;
for(var i=0;i<20;i++){
if(a[i]==searchkey){
document.write("item found");
break;
}
}
}
search();
</script>
</head>
<body>
</body>
</html>
2)
NOTE: You should study more about linear and binary search. The second part uses binary search algorithm.
<!DOCTYPE html>
<html>
<title>Web Page Design</title>
<head>
<script>
function binary_Search(items, value){
var firstIndex = 0,
lastIndex = items.length - 1,
middleIndex = Math.floor((lastIndex + firstIndex)/2);
while(firstIndex < lastIndex)
{if(middleIndex==value){
document.write("item found");
break;
}
else if (value < items[middleIndex])
{
lastIndex = middleIndex - 1;
}
else if (value > items[middleIndex])
{
firstIndex = middleIndex + 1;
}
middleIndex = Math.floor((lastIndex + firstIndex)/2);
}
return
}
var items = [1, 2, 3, 4, 5, 7, 8, 9];
(binary_Search(items, 1));
</script>
</head>
<body>
</body>
</html>