-
Notifications
You must be signed in to change notification settings - Fork 3
/
LinSearch.java
77 lines (66 loc) · 2.47 KB
/
LinSearch.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
Team Incredibly Cohesive (David Chen, Jaylen Zeng, Orion Roven)
APCS pd7
L03: Get Empirical
2021-12-16
time spent: .6 hrs
DISCO:
QCC:
*/
public class LinSearch {
/**
* int linSearch(Comparable[],Comparable) -- searches an array of
* Comparables for target
* post: returns index of first occurrence of target, or
* returns -1 if target not found
**/
public static int linSearch(Comparable[] a, Comparable target) {
int tPos = -1;
int i = 0;
while (i < a.length) {
if (a[i] == target) {
return i;
}
i++;
}
return tPos;
}
// utility/helper fxn to display contents of an array of Objects
private static void printArray(Object[] arr) {
String output = "[ ";
for (Object o : arr)
output += o + ", ";
output = output.substring(0, output.length() - 2) + " ]";
System.out.println(output);
}
// main method for testing
// minimal -- augment as necessary
public static void main(String[] args) {
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
System.out.println("\nNow testing linSearch on int array...");
// Declare an array of Comparables and initialize it using ints
// Each int will be autoboxed to class Integer,
// which implements Comparable.
Comparable[] iArr = { 2, 4, 6, 8, 6, 42 };
printArray(iArr);
// search for 6 in array
System.out.println(linSearch(iArr, 6));
// search for 43 in array
System.out.println(linSearch(iArr, 43));
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
System.out.println("\nNow testing linSearch on Comparable arrays...");
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
System.out.println("\nNow testing linSearch on String array...");
// declare and initialize an array of Strings
String[] sArr = { "kiwi", "watermelon", "orange", "apple",
"peach", "watermelon" };
printArray(sArr);
// search for "watermelon" in array
System.out.println(linSearch(sArr, "watermelon"));
// search for "lychee" in array
System.out.println(linSearch(sArr, "lychee"));
/*----------------------------------------------------
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
----------------------------------------------------*/
}// end main()
}// end class LinSearch