Home  >  Article  >  Backend Development  >  C++ program to search for specific value in array

C++ program to search for specific value in array

WBOY
WBOYforward
2023-08-30 19:21:06880browse

C++ program to search for specific value in array

Suppose we have an array "arr" containing n sorted integer values. We are also given an array "query" of size q and we have to tell if the value in "query" is present in the given array "arr". If the value in the query exists in arr, print "exists" and the location of the value. Otherwise, we print "does not exist" and prints the position in arr where the minimum value greater than the value in the query is located. We have to remember that arrays are 1-indexed.

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

Present 1
Not present 5
Not present 6

The first value of the query appears in position 1 of arr.

The second value of the query appears in arr. The position of the smallest value greater than the value in query is 5.

Similarly, there is no third value of query in arr. Values ​​greater than this are at position 6 of arr.

To solve this problem, we will follow the following steps -

  • Define an array value
  • For initialization i := 0, when i
  • Insert arr[i] at the end of the value
  • Initialize i := 0, when i
  • idx: = (the position of the first element in values ​​that is not less than query[i]) -the position of the first element in values
  • if values[idx] is the same as query[i], then -
    • print("Exists")
  • Otherwise,
    • print("Does not exist ")
  • print(idx 1)
  • Example

    Let us refer to the following implementation to get more Good 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 (standard input)

    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

    The above is the detailed content of C++ program to search for specific value in array. For more information, please follow other related articles on the PHP Chinese website!

    Statement:
    This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete