C++ example of a lookup algorithm in a two dimensional array

  • 2020-05-19 05:14:56
  • OfStack

This example demonstrates the lookup algorithm in an C++ 2-dimensional array. I will share it with you for your reference as follows:

1. The question is:

In a 2-dimensional array, each row is sorted in ascending order from left to right, and each column is sorted in ascending order from top to bottom. Please complete a function, enter such a 2 - dimensional array and an integer, determine whether the array contains the integer.

2. Implementation code:


#include <iostream>
#include <vector>
using namespace std;
bool Find(int target, vector<vector<int> > array) {
  int row = array.size();   // The number of rows   
  int column = array[0].size();  // The number of columns 
  int i = 0, j = column - 1;
  while (i < row && j >= 0)
  {
    if (array[i][j] == target) // From the top right 1 It's bigger than target Look to the left, less than target I'm looking down 
    {
      return true;
    }
    else if (array[i][j] > target)
    {
      j--;    // Look left 
    }
    else
    {
      i++;    // Scroll down 
    }
  }
  return false;
}
int main()
{
  vector<int> vec1{ 3, 7, 9, 12, 19, 23 };
  vector<int> vec2{ 4, 17, 19, 31, 32, 33 };
  vector<vector<int> > array;
  array.push_back(vec1);
  array.push_back(vec2);
  bool result = Find(32, array);
  cout << "result = " << result << endl;
  system("pause");
}

I hope this article is helpful to you C++ programming.


Related articles: