0

This is my solution to the problem of finding a value inside a C++ array:

#include <iostream>
#include <sys/resource.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h> 
#include <sys/types.h>
#include <algorithm>
#include <vector>

using namespace std;

class Answer
{
public:
    static bool exists(int ints[], int size, int k)
    {
        bool result = false;        
        for (int i = 0; i < size; i++)
        {
            if (ints[i] == k)
                result = true;
        }
        return result;
    }
};

The grader took points off citing the following reasons: img

What could I have done to meet their requirements?

4
  • 3
    is the input array sorted? Commented Jun 24, 2022 at 4:15
  • 1
    Do you understand what "binary search" is? If so, your code doesn't do that, and I see a big red X on the item marked as such. Commented Jun 24, 2022 at 4:19
  • 3
    The second thing is that you keep looping after you've found a result. At the very least, you should break out of the loop when you find the value. Commented Jun 24, 2022 at 4:22
  • Re: "What could I have done to meet their requirements?" Normally reading the question carefully helps a lot with this. Commented Jun 24, 2022 at 7:08

1 Answer 1

1

You are not implementing binary search, you could use binary_search or do it manually:

binary_search:

class Answer
{
public:
    static bool exists(int ints[], int size, int k)
    {
      return binary_search(ints, ints + size, k);
    }
};

manually:

class Answer
{
public:
    static bool exists(int ints[], int size, int k)
    {
      int low = 0;
      int high = size - 1;
      while (low <= high)
      {
        int mid = (low + high) / 2;
        if (ints[mid] == k)
        {
          return true;
        }
        else if (ints[mid] < k)
        {
          low = mid + 1;
        }
        else
        {
          high = mid - 1;
        }
      }
      return false;
    }
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.