Created
August 20, 2012 05:17
-
-
Save George3/3401180 to your computer and use it in GitHub Desktop.
Yahoo! Answers: Code for qid=20120819133145AAdBf2E
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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