why does accessing an element in an array take constant time?

user188276 picture user188276 · Sep 4, 2011 · Viewed 20.7k times · Source

Lets say I have an array as:

int a[]={4,5,7,10,2,3,6}

when I access an element, such as a[3], what does actually happen behind the scenes? Why do many algorithm books (such as the Cormen book...) say that it takes a constant time?

(I'm just a noob in low-level programming so I would like to learn more from you guys)

Answer

Reed Copsey picture Reed Copsey · Sep 4, 2011

The array, effectively, is known by a memory location (a pointer). Accessing a[3] can be found in constant time, since it's just location_of_a+3*sizeof(int).

In C, you can see this directly. Remember, a[3] is the same as *(a+3) - which is a bit more clear in terms of what it's doing (dereferencing the pointer "3 items" over).