Instantly share code, notes, and snippets.

@bytecodeman /LinearSearch.java Secret
Last active Sep 22, 2018

Embed
What would you like to do?
The Ultimate Linear Search Class V2.0
package silvestri;
public class LinearSearch {
public static int linearSearch(char[] list, int count, char key) {
if (count < 0 || count > list.length) {
String descriptor = "Bad Count!!! Count = %d list.length = %d";
throw new RuntimeException(String.format(descriptor, count, list.length));
}
for (int i = 0; i < count; i++) {
if (key == list[i])
return i;
}
return -1;
}
public static int linearSearch(char[] list, char key) {
return linearSearch(list, list.length, key);
}
public static int linearSearch(int[] list, int count, int key) {
if (count < 0 || count > list.length) {
String descriptor = "Bad Count!!! Count = %d list.length = %d";
throw new RuntimeException(String.format(descriptor, count, list.length));
}
for (int i = 0; i < count; i++) {
if (key == list[i])
return i;
}
return -1;
}
public static int linearSearch(int[] list, int key) {
return linearSearch(list, list.length, key);
}
public static int linearSearch(double[] list, int count, double key) {
if (count < 0 || count > list.length) {
String descriptor = "Bad Count!!! Count = %d list.length = %d";
throw new RuntimeException(String.format(descriptor, count, list.length));
}
for (int i = 0; i < count; i++) {
if (key == list[i])
return i;
}
return -1;
}
public static int linearSearch(double[] list, double key) {
return linearSearch(list, list.length, key);
}
public static int linearSearch(String[] list, int count, String key) {
if (count < 0 || count > list.length) {
String descriptor = "Bad Count!!! Count = %d list.length = %d";
throw new RuntimeException(String.format(descriptor, count, list.length));
}
for (int i = 0; i < count; i++) {
if (key.equals(list[i]))
return i;
}
return -1;
}
public static int linearSearch(String[] list, String key) {
return linearSearch(list, list.length, key);
}
public static int linearSearchIgnoreCase(String[] list, int count, String key) {
if (count < 0 || count > list.length) {
String descriptor = "Bad Count!!! Count = %d list.length = %d";
throw new RuntimeException(String.format(descriptor, count, list.length));
}
for (int i = 0; i < count; i++) {
if (key.equalsIgnoreCase(list[i]))
return i;
}
return -1;
}
public static int linearSearchIgnoreCase(String[] list, String key) {
return linearSearchIgnoreCase(list, list.length, key);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment