Advertisement
Guest User

LinearSearcher

a guest
May 27th, 2014
292
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.24 KB | None | 0 0
  1. /**
  2.    A class for executing linear searches through an array.
  3. */
  4. public class LinearSearcher
  5. {  
  6.    private int[] nums;
  7.  
  8.    /**
  9.       Constructs the LinearSearcher.
  10.       @param anArray an array of integers
  11.    */
  12.    public LinearSearcher(int[] anArray)
  13.    {
  14.       nums = anArray;
  15.    }
  16.  
  17.    
  18.    /**
  19.       Finds if a value exists in an array, using the linear search
  20.       algorithm.
  21.       @param target the value to search
  22.       @return true if it occurs in the array
  23.    */
  24.     public boolean contains(int target)
  25.     {
  26.         int index = 0;
  27.         while (index < nums.length && nums[index] != target)
  28.         {
  29.             index++;
  30.         }
  31.         return (index < nums.length);      
  32.    }
  33.  
  34.    /**
  35.       Finds a value in an array, using the linear search
  36.       algorithm.
  37.       @param target the value to search
  38.       @return the index at which the value occurs, or -1
  39.       if it does not occur in the array
  40.    */
  41.    public int search(int target)
  42.    {  
  43.         int index = 0;
  44.         while (index < nums.length && nums[index] != target)
  45.         {
  46.             index++;
  47.         }
  48.         if (index == nums.length)
  49.         {
  50.             index = -1;
  51.         }
  52.         return index;
  53.     }
  54.  
  55.    
  56.    
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement