Advertisement
CHU2

Recursive Linear Search

Mar 24th, 2023
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.63 KB | Source Code | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. int linearsearch(int array[], const int, int);
  6.  
  7. int main() {
  8.     const int size = 5;
  9.     int array[size] = { 5, 15, 6, 9, 4 };
  10.     int search = 4;
  11.  
  12.     int ans = linearsearch(array, size, search);
  13.  
  14.     if (ans != NULL) {
  15.         cout << "Element " << search << " present at index " << ans;
  16.     }
  17.     else {
  18.         cout << "Element " << search << " is not present in array";
  19.     }
  20.  
  21.     return 0;
  22. }
  23.  
  24. int linearsearch(int array[], const int size, int search) {
  25.     if (size == 0) {
  26.         return NULL;
  27.     }
  28.     else if (array[size - 1] == search) {
  29.         return size - 1;
  30.     }
  31.     else {
  32.         linearsearch(array, size - 1, search);
  33.     }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement