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)
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).