Hey guys!!

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 {
}
}

}``````

Thanks! :)

You could use compareTo() for string function. If compareTo() return -1, the string which calls the function is less than (shorter or alphabet comes before) the comparing string which is passed as an argument. It should find 0 or return -1 if it returns 1.

``````public int find(final String[] data, final String key) {
for (int i = 0; i < data.length; ++i) {
if (data[i].compareTo(key)<0) {
...
}
else if (...) {
...
...
}
else {
...
}
...
}
}``````

You could also use compareToIgnoreCase() if you want a case-insensitive comparison.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.