//COMPUTER SCIENCE 161.01 //FRIDAY APRIL 5th 2013 //SEQUENTIAL SEARCH (a.k.a. LINEAR SEARCH) //THE PROGRAM BELOW PERFORMS THE SEQUENTIAL SEARCH ALGORITHM //IT IS ALSO KNOWN AS THE 'LINEAR' SEARCH ALGORITHM //BECAUSE IT REQUIRES AT MOST N COMPARISONS WHERE N IS SIZE OF LIST //HERE, N is 15. firstNames = new Array("Derek", "Tyler", "Kyle", "Hunter", "Tanner", "Aaron", "Charles", "Paul", "Elijah", "Alex", "Devin", "Loren", "Tyler", "Brian", "Cody"); lastNames = new Array("Fimian", "Lange", "Fraser", "Guttendorf", "Iglio", "Van Allen", "MacSherry", "Boydoh", "Hawkins", "Smith", "Baker", "Hubbard", "Johnson", "Hulsizer", "Joyner"); i=0; desiredName = prompt("Enter the last name of the person you wish to greet:"); while (i < lastNames.length) { if (lastNames[i] == desiredName) //IF CURRENT lastName MATCHES desiredName alert("Happy Monday to " + firstNames[i]); //THEN send a friendly greeting using firstName i++; } alert("ALL DONE"); //WE NEED TO IMPROVE THIS, BECAUSE THE ABOVE PROGRAM ALWAYS MAKES 15 COMPARISONS //EVEN IF WE WERE LOOKING FOR Fimian. //1) I WANT TO NOT MAKE ANY UNNECESSARY COMPARISONS ONCE I FIND A MATCH //Here's where we introduced and used the boolean variable 'found' //2) AS A SECOND IMPROVEMENT, LET'S REPORT WHETHER OR NOT THE desired NAME WAS FOUND! //This is the if-else statement after the while loop. firstNames = new Array("Derek", "Tyler", "Kyle", "Hunter", "Tanner", "Aaron", "Charles", "Paul", "Elijah", "Alex", "Devin", "Loren", "Tyler", "Brian", "Cody"); lastNames = new Array("Fimian", "Lange", "Fraser", "Guttendorf", "Iglio", "Van Allen", "MacSherry", "Boydoh", "Hawkins", "Smith", "Baker", "Hubbard", "Johnson", "Hulsizer", "Joyner"); i=0; desiredName = prompt("Enter the last name of the person you wish to greet:"); found = false; while ( !found && i < lastNames.length) { //while not found yet and still more names if (lastNames[i] == desiredName) //if current lastName matches desiredName found = true; //set found to true, thus ending the loop else //otherwise move along to the next name. i++; } if (found) alert("Happy Monday to " + firstNames[i]); else alert(desiredName + " was not found."); alert("ALL DONE");