Skip to content

Instantly share code, notes, and snippets.

@t81lal
Created January 30, 2015 22:05
Show Gist options
  • Save t81lal/bca720ddd1d01785b9ff to your computer and use it in GitHub Desktop.
Save t81lal/bca720ddd1d01785b9ff to your computer and use it in GitHub Desktop.
import java.util.Scanner;
public class SearchMain {
public static void main(String args[]) {
String[] array = { "Alpha", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot", "Golf", "Hotel", "India", "Juliet", "Kilo", "Lima", "Mike", "November", "Oscar", "Papa", "Quebec",
"Romeo", "Sierra", "Tango", "Uniform", "Victor", "Whiskey", "X-Ray", "Yankee", "Zulu" };
Scanner scanner = new Scanner(System.in);
String word = "";
char again;
do {
System.out.println("What word do you need to find?");
word = scanner.nextLine();
linearSearch(array, word);
binarySearch(array, word);
System.out.println("Do you want do search another?(y/n)");
again = scanner.next().charAt(0);
scanner.nextLine();
} while ((again == 'y') || (again == 'Y'));
System.out.println("You have completed your searches.");
scanner.close();
}
public static void linearSearch(String[] array, String target) {
int index = 0;
while (index < array.length) // sequential search { } if
// (found) return index;
// else { }
{
if (array[index].equals(target)) {
System.out.println("Linear found it at " + index);
break;
} else {
index++;
}
}
/* Create a linear search where you will go through the arrayand search
* for the target word.
*
* The output of this class should output: -number of words you checked
* -the index of the word */
}
public static void binarySearch(String[] array, String target) {
int lowerbound = 0;
int upperbound = array.length - 1;
boolean found = false;
while (!found) {
int index = (lowerbound + upperbound) / 2;
String curr = array[index];
if (curr.compareTo(target) > 0) {
upperbound = index - 1;
} else if (curr.compareTo(target) < 0) {
lowerbound = index + 1;
} else {
System.out.println("Binary found it at " + index);
found = true;
}
/* Create a binary search where you will go through the array and
* search for the target word.
*
* The output of this should output: -number of words you checked
* -the index of the word */
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment