Why is accessing any single element in an array done in constant time ( O(1) )?

后端 未结 5 826
灰色年华
灰色年华 2020-12-14 04:32

According to Wikipedia, accessing any single element in an array takes constant time as only one operation has to be performed to locate it.

To me, what happens behi

5条回答
  •  余生分开走
    2020-12-14 04:42

    Accessing a single element is NOT finding an element whose value is x.

    Accessing an element i means getting the element at the i'th position of the array.

    This is done in O(1) because it is pretty simple (constant number of math calculations) where the element is located given the index, the beginning of the array and the size of each element.

    RAM memory offers a constant time (or to be more exact, a bounded time) to access each address in the RAM, and since finding the address is O(1), and retrieving the element in it is also O(1), it gives you total of O(1).

    Finding if an element whose value is x is actually Omega(n) problem, unless there is some more information on the array (sorted, for example).

提交回复
热议问题