Skip to content

Instantly share code, notes, and snippets.

@George3
Created August 20, 2012 05:17
Show Gist options
  • Save George3/3401180 to your computer and use it in GitHub Desktop.
Save George3/3401180 to your computer and use it in GitHub Desktop.
Yahoo! Answers: Code for qid=20120819133145AAdBf2E
/**
* From Yahoo! Answers: "Writing a Java linear search algorithm that
* uses generics and has an array that store any data..."
* http://answers.yahoo.com/question/index?qid=20120819133145AAdBf2E
*/
public class LinearStringSearch {
public static <AnyType extends Comparable<? super AnyType>> int LinearSearch(
AnyType target, AnyType[] sa) {
for (int i = 0; i < sa.length; ++i) {
if (sa[i] == target) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
Integer[] list = new Integer[6];
for (int i = 0; i < list.length; ++i) {
list[i] = i;
}
int result = LinearSearch(new Integer(3), list);
if (result == -1) {
System.out.println("Not found");
} else {
System.out.println("[] = \"5\"");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment