Sorting Algorithm

Assignment 3

by Jake Jernigan

HTML

Choose a number between 1 and 1000:
<br/>
<br/>
<input type="textbox" id="value" number="" />
<input type="button" id="button1" value="Run Program" onClick="searchArray();" />
<br/>
<br/>
<div id="output">
</div>

JavaScript

var array = new Array(1000);
var display = "";

function fillArray() {
  for (var i = 0; i < array.length; i++) {
    array[i] = i + 1;
  }
}

function searchArray() {
  clearDisplay();
 
  var min = 0;
  var max = 999;
 
  var guessCount = 0;
  var potential = Math.floor((max + min) / 2);
  var actual = parseInt(document.getElementById('value').value);
  
  // TRY TO GET A TYPEOF (typeof "John" returns string) TO WORK FOR OTHER NON VALID ANSWERS
  // POSSIBLY LOOK INTO NON VALUE ANSWERS THAT CRASHES THE PROGRAM
  if (actual < 1 || actual > 1000) {
    display = actual + " is not valid. Pick a numbet from 1 to 1000";
    document.getElementById("output").innerHTML = display;

  } else {
    while (array[potential] != actual) {
      
      if (array[potential] < actual) {
        
        //LOOKING AT LOW CASE
        display += "Guessed " + array[potential] + " - Too low. <br/>";
        document.getElementById("output").innerHTML = display;
        min = potential + 1;
        potential = Math.round((max + min) / 2);
     
     } else {
        
        //LOOKING AT HIGH CASE 
        display += "Guessed " + array[potential] + " - Too high. <br/>";
        document.getElementById("output").innerHTML = display;
        max = potential - 1;
        potential = Math.round((max + min) / 2);
    
     }
      
      guessCount++;
    
    }
    guessCount++;
    //FINAL PORTION 
    display += "Guessed " + array[potential] + " - Just right. <br/><br/>" + 
    	      	 "This program took " + guessCount + " tries to obtain the correct answer.";
    document.getElementById("output").innerHTML = display;
  }
}

fillArray();

function clearDisplay() {
  display = "";
  document.getElementById("output"), innerHTML = "";
}