Why search in array O (1)?

I believe that in some languages โ€‹โ€‹other than Ruby, searching in an array is O (1), because you know where the data starts, and you multiply the index by the size of the data stored in the array, and then access this memory location and etc.

However, in Ruby, an array can have objects from different classes, so how does it manage to search for O (1) complexity?

+5
source share
2 answers

What @Neil Slater said, a little more ...

In principle, there are two plausible approaches to storing an array of heterogeneous objects of different sizes:

  • Store the objects as a separate or doubly linked list with storage space for each individual object that is preceded by a pointer (s) to the previous and / or next objects. The advantage of this structure is that it is very easy to insert new objects at arbitrary points without moving around the rest of the array, but the huge disadvantage is that searching for an object by its position is usually O(N) , since you must start with one end of the list and slip through it node-by-node until you come to the nth.

  • Keep a table or array of constant-size pointers for individual objects. Since this lookup table contains elements with a constant size in an adjacent ordered layout, the address search for individual objects is O(1) ; the table is just an array of C-style, in which the search requires only 1 machine instructions even on the architecture of the CPU RISC.

(Distribution strategies for storing individual objects are also interesting and complex, but do not immediately relate to your question.)

Dynamic languages โ€‹โ€‹like Perl / Python / Ruby are pretty much opting for # 2 for their types / types of general-purpose arrays. In other words, they make searching more efficient than pasting objects into random locations in a list, which is the best choice for many applications.

I am not familiar with the details of the Ruby implementation, but they are most likely similar to the Python list types whose performance and design are described in detail in effbot.org .

+6
source

Its implementation probably contains an array of memory addresses pointing to actual objects. Therefore, it can still search without a loop through the array.

+4
source

Source: https://habr.com/ru/post/1201301/


All Articles