Search Algorithm

Assignment 3

by Alan Harris

HTML

<label>What is Your Guess Between 1 and 1000? </label><br><br>
<input id="user_Guess" type="textbox" value="1">
<br><br>


<button id="userButton" onclick="createArray();">Sumbit Guess</button>


<br><br><div id="output"></div>

CSS

label {
  font-size:18px;
}


#user_Guess:focus {
  border: 1px solid black;
  padding: 4px 4px;
}

#userButton {
    background-color: grey;
    border: 1px solid black;
    color: white;
    padding: 4px 8px;
    text-decoration: none;
    margin: 4px 2px;
    }
 #userButton:hover {
   background-color:black;
 }

JavaScript

var array = [];
var display = "";

function createArray() {
	
	var arraysize = 1000;
  
	for(var i=0; i <= arraysize; i++) {
  	array[i] = i;
  }
  search();
}

function search() {
display = "";

	var user_input = parseInt(document.getElementById("user_Guess").value);
  if (user_input < 1 || user_input > 1000) {
  	display = "Please type in a number between 1 and 1000.";
    document.getElementById("output").innerHTML = display;
  }
  else {
  var min = 1;
  var max = 999;
  var mid = Math.round((max + min)/2); 
  var incr = 1;

while (array[mid] != user_input) {
       
        if (array[mid] < user_input) {
            display += "Computer guessed " + array[mid] + ", too low! <br/>";
            document.getElementById("output").innerHTML = display;
            min = mid + 1;
            mid = Math.round((max + min)/2);
            }
       
        else {
            display += "Computer guessed " + array[mid] + ", too high! <br/>";
            document.getElementById("output").innerHTML = display;
            max = mid - 1;
            mid = Math.round((max + min)/2);
            }
                incr++;
}
display += "Computer guessed " + array[mid] + ", right on the dot! <br/>  It took the computer " + incr + " tries to find your number.";
document.getElementById("output").innerHTML = display;
  } 
}