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

Merge two sorted arrays together

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

Problem

Please review my answer for this interview question:

#include 
#include 

std::vector merge2Sorted ( std::vector left, std::vector right )
{
  //finger matching algo

  auto itLeft = left.begin();
  auto itRight = right.begin();

  auto itLeftEnd = left.end();
  auto itRightEnd = right.end();

  std::vector result;
  result.reserve(std::max(left.size(),right.size())); 

  while ( itLeft != itLeftEnd && 
          itRight != itRightEnd )
  {
    if ( *itLeft  v1 = { 1,2,3,4,5,6,7,8,9,10 };
  std::vector v2 = { -1,-2,0,3,7,9,11,12 };

  std::vector v3 ( merge2Sorted ( v1, v2 ) );

  for ( auto& i: v3 )
    std::cout << i << std::endl;
}

Solution

Pass your parameters by const reference to avoid a copy:

std::vector merge2Sorted(std::vector const& left, std::vector const& right)
//                                             ^^^^^^                        ^^^^^^


You are not reservng enough

result.reserve(std::max(left.size(),right.size()));


The result size will eventually be the size of the sum of the two input arrays.

result.reserve(left.size() + right.size());


Your test for left and right can be simplified:

if ( *itLeft < *itRight )
  result.push_back( *itLeft++ );
else
  result.push_back( *itRight++ );
}

// Simplified
// Though I am 50/50 on this one.
result.push_back( ( *itLeft < *itRight ) ? *itLeft++ : *itRight++);


No point in flushing the stream after every print:

std::cout << i << std::endl;

                  ^^^^^^^^^^  prefer '\n' unless you really want to force a flush.

std::cout << i << '\n';

Code Snippets

std::vector<int> merge2Sorted(std::vector<int> const& left, std::vector<int> const& right)
//                                             ^^^^^^                        ^^^^^^
result.reserve(std::max(left.size(),right.size()));
result.reserve(left.size() + right.size());
if ( *itLeft < *itRight )
  result.push_back( *itLeft++ );
else
  result.push_back( *itRight++ );
}

// Simplified
// Though I am 50/50 on this one.
result.push_back( ( *itLeft < *itRight ) ? *itLeft++ : *itRight++);
std::cout << i << std::endl;

                  ^^^^^^^^^^  prefer '\n' unless you really want to force a flush.

std::cout << i << '\n';

Context

StackExchange Code Review Q#35397, answer score: 7

Revisions (0)

No revisions yet.