Advertisement
avr39ripe

SBU021LinearSearch

Aug 1st, 2020
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.81 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. int linearSearch(int arr[], int arrSize, int key)
  4. {
  5.     int resIdx{ -1 };
  6.  
  7.     for (int i{ 0 }; i < arrSize; ++i)
  8.     {
  9.         if (arr[i] == key)
  10.         {
  11.             resIdx = i;
  12.             break;
  13.         }
  14.     }
  15.  
  16.     return resIdx;
  17. }
  18.  
  19. int main()
  20. {
  21.     const int arrSize{ 10 };
  22.     int arr[arrSize]{ 6,1,4,2,8,9,11,3,2,1 };
  23.     //int arr[arrSize]{ 1,1,1,2,2,9,11,1,2,1 };
  24.     //int arr[arrSize]{ 1,2,3,4,5,6,7,8,9,10 };
  25.     //int arr[arrSize]{ 1,2,3,4,5,6,7,9,8,7 };
  26.     //int arr[arrSize]{ 10,9,8,7,6,5,4,3,2,1 };
  27.     //int arr[arrSize]{0};
  28.     int key{ 1 };
  29.     int idx{};
  30.  
  31.     idx = linearSearch(arr, arrSize, key);
  32.  
  33.     if (idx >= 0)
  34.     {
  35.         std::cout << "Search key was " << key <<
  36.             " result index is " << idx <<
  37.             " arr[resIdx] = " << arr[idx] << '\n';
  38.     }
  39.     else
  40.     {
  41.         std::cout << "Search key was " << key << ". Search key NOT FOUND!\n";
  42.     }
  43.    
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement