Scan an array and return the position of a target.
Linear search in Java
Implementation
static int find(int[] values, int target) {
for (int i = 0; i < values.length; i++) {
if (values[i] == target) return i;
}
return -1;
}Reasoning
In the worst case every element is checked, so time grows linearly with array length. Extra space stays constant. This version assumes a non-null array.
Check
Try a target at the first position, at the last position and a missing target.
Common Mistakes
Check empty inputs and invalid values before applying this operation to application data. State whether a method edits shared state or returns a separate value.
java-dsa
