HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Determine if an element exists in a sorted NxN matrix

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
elementdetermineexistssortedmatrixnxn

Problem

The point of this algorithm is to see if an element exists in a NxN matrix that has its rows and columns sorted.

What would you change? What did I do well? Both perspectives help so I am not left guessing.

```
#include
#include
#include
#include
#include
#include
/ Author: Matthew Everett Hoggan /
/ Date: August 8, 2011 /
/ Problem Statement: /
/ Given an matrix such that every row is sorted and every column is sorted /
/ write a function "find_kth_element_and_return_rowXcol" that returns a /
/ a pair where the element was found. If it is not found return /
/ to indicate to user that their value was not found /

namespace Matrix
{
/ This class is designed to solve the problem at hand /
/ The method definitions are described where they are defined /
/ Note this matrix is a N x N square matrix /
class RandomOrderedMatrix
{
public:
RandomOrderedMatrix( int N );
~RandomOrderedMatrix( );
void find_element( int element );
void print_matrix( );
std::pair& get_coord( ) { return this->data; }
private:
void build_matrix( );
int **matrix;
std::pair data;
int N;
friend std::ostream& operator d = rom.data;
return out " N = N;
this->matrix = new int*[N];
for( int r=0;rbuild_matrix( );
}

/ dtor /
RandomOrderedMatrix::~RandomOrderedMatrix( )
{
if( matrix )
{
for( int r=0;r= matrix[r][0] && element left_index ) {
int middle = (right_index+left_index)/2;
if( element == matrix[r][middle] )

Solution

I would replace:

int **matrix;


with:

std::vector >  matrix; /* or Boost::Matrix */


Then your constructor/destructor become:

RandomOrderedMatrix::RandomOrderedMatrix( int N )
    : matrix(N, std::vector(N))

    // , N(N)   Don't need this anymore size is part of the vector
{
    build_matrix( );
} 

/* dtor                                                                  */
// Don't need the de-structor


This also solves the problem of not obeying the "rule of three".

Move this:

srand((unsigned)time(NULL));


To the first line of main() (note your build matrix uses rand() which is happening before the call to srand() thus you are not getting random numbers).

Code Snippets

int **matrix;
std::vector<std::vector<int> >  matrix; /* or Boost::Matrix */
RandomOrderedMatrix::RandomOrderedMatrix( int N )
    : matrix(N, std::vector<int>(N))

    // , N(N)   Don't need this anymore size is part of the vector
{
    build_matrix( );
} 

/* dtor                                                                  */
// Don't need the de-structor
srand((unsigned)time(NULL));

Context

StackExchange Code Review Q#4003, answer score: 5

Revisions (0)

No revisions yet.