class Binary_Search
{
search()
{
var c, first, last, middle, n, search;
var x;
var array: number[] = [30];
n = parseInt(prompt("Enter how many elements you want: \n"));
for (c = 0; c < n;c++)
array[c]=parseInt(prompt("Enter "+n+" integers"));
for (x = 0; x < n; x++)
{
var span = document.createElement("span");
span.style.color = "Green";
span.innerText = "Enter "+ x +" Element -> " + array[x]+ "\n";
document.body.appendChild(span);
}
search = parseInt(prompt("Enter value to search\n"));
first = n;
last = 1;
do
{
middle = Math.floor((last + first) /2);
if (search < array[middle])
first = middle - 1;
elseif (search > array[middle])
last = middle+ 1;
}
while (search != array[middle] && last <= first)
if (search == array[middle])
{
var x = middle + 1;
var span = document.createElement("span");
span.style.color = "Blue";
span.innerText ="\nBinary search successfull!!\n"+ search+" Found in at Position: "+x+"\n";
document.body.appendChild(span);
}
else
{
alert("\n Search failed" +search+" not found\n"+search);
}
}
}
window.onload = () =>
{
var greeter = new Binary_Search();
greeter.search();
};
|