Advertisement
reellearning

Linear Search

Jun 28th, 2012
8,003
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.83 KB | None | 0 0
  1. /*
  2.  * linearsearch.cpp
  3.  *
  4.  *  Created on: Jun 28, 2012
  5.  *      Author: Derek
  6.  *
  7.  *  Example of linear search
  8.  */
  9.  
  10.  
  11. #include <iostream>
  12. using namespace std;
  13.  
  14.  
  15. int linearSearch(int array[], int size, int searchValue)
  16. {
  17.     for(int i = 0; i < size; i++)
  18.     {
  19.         if (searchValue == array[i])
  20.         {
  21.             return i;
  22.         }
  23.     }
  24.  
  25.     return -1;
  26. }
  27.  
  28. int main()
  29. {
  30.     int a[] = {15, 23, 7, 45, 87, 16};
  31.  
  32.     int userValue;
  33.  
  34.     cout << "Enter an integer: " << endl;
  35.     cin >> userValue;
  36.  
  37.     int result = linearSearch(a, 6, userValue);
  38.  
  39.     if(result >= 0)
  40.     {
  41.         cout << "The number " << a[result] << " was found at the"
  42.                 " element with index " << result << endl;
  43.     }
  44.     else
  45.     {
  46.         cout << "The number " << userValue << " was not found. " << endl;
  47.     }
  48.  
  49.  
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement