Hey guys!!
first off please dont tell me to google it, iv already done my searching with google and various text books lol ...
Ok So i understand how to find numbers in a linear search by inputting 10 numbers and searching. Now i need to do the same except now i am searing a given string of names.
String[] names = { "fred" , "barney", "tom", "jerry", "larry", "moe", "curly",
"betty" , "wilma", "bart", "homer", "marge", "maggie", "lisa",
"pebbles" , "bambam", "smithers", "burns", "milhouse", "george", "astro",
"dino" , "mickey", "minnie", "pluto", "goofy", "donald", "huey",
"louie" , "dewey", "snowwhite", "happy", "doc", "grumpy", "sneezy",
"dopey" , "sleepy", "bambi", "belle", "gaston", "tarzan", "jane",
"simba" , "scar", "mufasa", "ariel", "flounder", "bugs", "daffy",
"elmer" , "foghorn", "chickenhawk", "roger", "jessica", "hank", "bobby",
"peggy" , "spot", "pongo", "perdy", "buzz", "potatohead", "woody",
"chuckie" , "tommy", "phil", "lil", "angelica", "dill", "spike",
"pepe" , "speedy", "yosemite", "sam", "tweety", "sylvester", "granny",
"spiderman" , "batman", "superman", "supergirl", "robin", "jimmy", "olsen",
"thing" , "flash", "silversurfer", "xmen", "pokemon", "joker", "wonderwoman"
};
String[] sortednames = new String[names.length]; // will contain a sorted copy of names Array]
Im suppose to be commanded to write a name then it is going to search that string return the name if found and its position
Now the real question is how can i relate my previous code and change it into a linear search of names
import java.util.*;
public class LinearSearch {
public int find(final int[] data, final int key) {
for (int i = 0; i < data.length; ++i) {
if (data[i] > key)
return -1;
else if (data[i] == key)
return i;
}
return -1;
}
public static void main(String[] args) {
final int arr[] = new int[10];
System.out.println("Enter 10 numbers");
Scanner input = new Scanner(System.in);
for (int i = 0; i < arr.length; i++) {
arr[i] = input.nextInt();
}
LinearSearch search = new LinearSearch();
System.out.print("Enter the element to search: ");
int num=input.nextInt();
int n = search.find(arr, num);
if ((n >= 0) && (n < arr.length)) {
System.out.println("Found at index: " + n);
} else {
System.out.println("Not Found");
}
}
}
Thanks! :)