C++ Help with exercise

Hello , I am doing some exercises at home and this one is giving me some trouble. I would really appreciate some help.

The aim of this exercise is to check the presence of a number in an array.

Specifications:

  • The items are integers arranged in ascending order.
  • The array can contain up to 1 million items
  • The array is never NULL

Implement the method bool Answer::exists(int ints[], int size, int k) so that it returns true if k belongs to ints , otherwise the method should return false . size contains the size of ints .

Important note: Try to save CPU cycles if possible.

Example:
int ints[] = {-9, 14, 37, 102};
Answer::exists(ints, 4, 102) returns true
Answer::exists(ints, 4, 36) returns false

Firstly, welcome to the forums.

While we are primarily here to help people with their Free Code Camp progress, we are open to people on other paths, too. Some of what you are asking is pretty trivial in the Free Code Camp context, so you might find that if you’re not getting the instruction and material you need in your current studies, the FCC curriculum will really help you get started. At a modest guess I’d say investing a 4-5 hours working through the curriculum here will really pay off. You can find the curriculum at https://www.freecodecamp.org/learn.

With your current questions, we don’t have enough context to know what you already know or don’t know, so it is impossible to guide you without just telling you the answer (which we won’t do).

It is pretty typical on here for people to share a codepen / repl.it / jsfiddle example of what they have tried so that anyone helping has more of an idea of what help is actually helpful.

Please provide some example of what you’ve tried and I’m sure you’ll get more help.

Happy coding :slight_smile:

So the obvious way is to just start at the beginning of the array and work your way through until you find the number you are looking for or, because these are arranged in ascending order, you get to a number that is higher than what you are looking for. This would be O(n) which isn’t bad.

But if you are really trying to save CPU cycles then I think you could do better. You need to take advantage of the fact that these are arranged in ascending order. Don’t you think it would save a lot of CPU time if you could basically reduce the size of the array you are looking through by half each time you checked if k is in it?