0

Bit of a random question for you. If you have a method that has to check every single individual place inside an array, would it be okay to say that this method has notation of O(n)?

The reason i'm not sure if my answer is correct is due to the fact that as far as i'm aware O(n) relates to the number of items held in the array, while my assumption is based on the actual size of the array?

  • 1
    It's not clear what the difference is between "the number of items held in the array" and "the actual size of the array." – Bill the Lizard Jan 14 '15 at 18:32
  • It's more of a general question really? If you have to search every single position inside an array would the performance be O(N)???? It's a linear search from start to finish and every position would be looked at regardless of how full the array is? –  Jan 14 '15 at 18:32
  • For example, size of array is 20 and it has 10 spaces filled. –  Jan 14 '15 at 18:34

1 Answers1

0

If your algorithm has to look at every item in the array, that algorithm is O(n). If doesn't really matter if the array is full or not, since you can be flexible in how you define n. It can be either the size of the array or the number of non-null elements in the array. If your algorithm has to look in empty array slots to see if they're empty or not, use the size. (If that's a real performance issue, probably a different data structure is called for.)

For a really contrived example, if it takes one hour to process each non-null array element, but one nanosecond to check for null, then you should define n to be the number of elements that actually exist, because that's what's going to dictate how the algorithm scales.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880