C++ program to search specific values in an array


Suppose we are given an array 'arr' that contains n number of sorted integer values. We are also given an array 'query' of size q, and we have to tell either the values in ‘query’ are present in the given array 'arr' or not. If a value in query is present in arr, we print "Present" along with the position where the value is situated in. Otherwise, we print "Not present" and print the position in arr, where the minimum value greater than the value in query is located. We have to remember that the arrays are 1-indexed.

So, if the input is like n = 8, arr = {1, 2, 3, 4, 7, 9, 12, 15} , q = 3, query = {1, 5, 8}, then the output will be

Present 1
Not present 5
Not present 6

The first value of queries is present in position 1 in arr.

The second value of queries is not present in arr. The position where the minimum value greater than the value in queries is 5.

Similarly, the third value of queries is also not present in arr. The value that is greater than it is in position 6 of arr.

To solve this, we will follow these steps −

  • Define an array values
  • for initialize i := 0, when i < n, update (increase i by 1), do −
    • insert arr[i] at the end of values
  • for initialize i := 0, when i < q, update (increase i by 1), do −
    • idx := (position of the first element in values that is not less than query[i]) - the first element position in values
    • if values[idx] is same as query[i], then −
      • print("Present ")
    • Otherwise,
      • print("Not present ")
    • print(idx + 1)

Example

Let us see the following implementation to get better understanding −

#include <vector>
#include <iostream>
using namespace std;

void solve(int n, int arr[], int q, int query[]) {
   vector<int> values;
   for(int i = 0; i < n; i++){
      values.push_back(arr[i]);
   }
   for(int i = 0; i < q; i++) {
      int idx = lower_bound (values.begin(), values.end(),
      query[i]) - values.begin();
      if (values[idx] == query[i])
         cout << "Present ";
      else
         cout << "Not present ";
      cout << idx + 1 << endl;
   }
}
int main() {
   int input_arr[] = {1, 2, 3, 4, 7, 9, 12, 15};
   int query_arr[] = {1, 5, 8};
   solve(8, input_arr, 3, query_arr);
   return 0;
}

Input(stdin)

int input_arr[] = {1, 2, 3, 4, 7, 9, 12, 15};
int query_arr[] = {1, 5, 8};
solve(8, input_arr, 3, query_arr);

Output

Present 1
Not present 5
Not present 6

Updated on: 11-Oct-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements