Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- A class for executing linear searches through an array.
- */
- public class LinearSearcher
- {
- private int[] nums;
- /**
- Constructs the LinearSearcher.
- @param anArray an array of integers
- */
- public LinearSearcher(int[] anArray)
- {
- nums = anArray;
- }
- /**
- Finds if a value exists in an array, using the linear search
- algorithm.
- @param target the value to search
- @return true if it occurs in the array
- */
- public boolean contains(int target)
- {
- int index = 0;
- while (index < nums.length && nums[index] != target)
- {
- index++;
- }
- return (index < nums.length);
- }
- /**
- Finds a value in an array, using the linear search
- algorithm.
- @param target the value to search
- @return the index at which the value occurs, or -1
- if it does not occur in the array
- */
- public int search(int target)
- {
- int index = 0;
- while (index < nums.length && nums[index] != target)
- {
- index++;
- }
- if (index == nums.length)
- {
- index = -1;
- }
- return index;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement