Why is the complexity of fetching from an Array be O(1)?

Technology CommunityCategory: ArraysWhy is the complexity of fetching from an Array be O(1)?
VietMX Staff asked 3 years ago
Problem

I thought the algorithm has to go through all the indexes, find the correct index, and then know what value to return. So that means the complexity is O(n/2) on average. Why is it actually O(1)?

The key to understanding why array access is O(1) is understanding that they have a known length. In a language like C, we can guarantee this by allocating a sequential block of memory. Since it’s sequential in memory, we can use pointer arithmetic for direct addressing and thus direct access. The compiler knows the array to start at memory cell x. When it needs to get to a123, it adds 123 * elementSize to x and uses that number to address the memory to get to the element.

This addition is also why in C and C++ at least, all items in an array need to be the same type (to keep same elementSize). They all are required to occupy the same number of bytes for this pointer arithmetic to work.