Two Questions

I'm trying to get correct answers from my exam to study for a midterm:

Write a function that returns the maximum value of an array of doubles.

Declaration:

double maximum(array[],int a_size);

Now I need help making the definition. So far I've done:

1
2
3
4
5
6
7
8
9
10
11
double maximum(array[], int a_size)
{
 double maxVal;
 maxVal = array[0];
 for(int i=1; i < size; i++)
 {
   if(array[i] > max
   maxVal=array[i]
 }
   return maxVal;
}


I just need any corrections.


Second, I need to write a function definition that merges two vectors containing integers, alternating elements from both vectors.

Prototype:

vector<int> merge(const vector<int> a, const vector<int> b);

This is my definition so far:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
vector<int>merge(const vector<int> a, const vector<int> b)
{
  vector<int> merged;
  for(int i=0; i<a.size+b.size; i++)
  {
   if(flag == true)
   merged.push_back(a);
   flag = false;
   else
   merged.push_back(b)
   flag = true;

  
}


I think I'm lost in the second part...




Last edited on
For the first problem, line 7 should probably be
if (array[i]>maxVal)
Also, it won't work if the a_size <= 0. You may want to return NaN in that case.

For the second problem you can simplify it by pushing one item from a and one from b each time through the loop:
1
2
3
4
for (int i=0; i<a.size(); ++i) {
    merged.push_back(a[i]);
    merged.push_back(b[i]);
}


But this assumes that both arrays are the same size. Can you make that assumption?

Also, pass a and b by reference instead of by value.
Last edited on
Yes, OP does need to watch indentation and braces, but I don't think he is missing anything important here.

a.size() cannot be less than zero.
However, if a.size() equals zero, then OP has a problem. Test for that.
By convention, the maximum value of an empty set is zero. (Not NaN.)

For the second problem, neither solution is correct. The point of merging two ordered sets is:
- given two choices (first item in a and first item in b)
- take the smallest[1] and append it to the result.
Repeat until both a and b are exhausted.

1 (It need not be the smallest, per se, it need be the item that comes first in the final set.)

Hope this helps.
Topic archived. No new replies allowed.