I think typically, insertion to the middle (any where) of an array can be costly — it can take O(n) time to shift the elements over one slot, and possibly reallocation of memory for the array. On the other hand, a linked link can take O(1) time.
But in Ruby, Python, and PHP, is there an array object that only takes O(1) time to insert an element in the middle of the array?
update: And it has to follow that the replacement of the array element any where in the array or accessing it is also O(1).
update: insertion as in the following:
1.9.3-p125 :001 > RUBY_DESCRIPTION
=> "ruby 1.9.3p125 (2012-02-16 revision 34643) [x86_64-darwin11.3.0]"
1.9.3-p125 :002 > a = %w{ a b c d }
=> ["a", "b", "c", "d"]
1.9.3-p125 :007 > a.insert(3, 123)
=> ["a", "b", "c", 123, "d"]
In PHP, you have
\SplDoublyLinkedListthat can do this for you. http://php.net/manual/en/class.spldoublylinkedlist.phpNote that PHP arrays are not arrays that you see in C, C#, Java, etc – they are ordered hash maps. See the intro of http://www.php.net/manual/en/language.types.array.php
Depending on your use case (if this isn’t homework),
\SplMaxHeapisn’t O(1) but may be your optimal choice. http://php.net/manual/en/class.splmaxheap.php