Join the Stack Overflow Community
Stack Overflow is a community of 6.9 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I have an array where I insert values with numeric keys associated with them. My problem is that when I insert a value with key less than a key which has been inserted before it comes after the larger key in the array i.e, it is the next element not the previous one(but the key is smaller). I don't want to apply sorting as I don't have much time limit and data is large. Later I need to search the array for a particular key and value pair. Therefore I can't use array pad to initialize the array(length of array is 100000). Because if I do it, the search would be really slow. I just want the key value pair (which I insert) to be in array but I wish that a key with lesser numeric value should automatically become previous element to a key with greater numeric value. For example:

$a[0]=1;
$a[25]=2;
$a[12]=3;

Here $a[12] should be the second element of the array but as I use foreach to excess every element, it comes out to be the third element.

share|improve this question
2  
So you want the array sorted, without sorting it? Good luck with that. – vascowhite Feb 5 '12 at 8:06
1  
i just wanted to say that if key '12' is less than '25' then it must come before it (as both are numeric) – Sushant Kochar Feb 5 '12 at 10:11
up vote 3 down vote accepted

You can't get sorting for free. Initialize the array with a simple foreach loop. Either that or bite the bullet and either a) sort at the end or b) do a sort after each element is inserted.

share|improve this answer
    
a better solution would be to insert the element with array_slice after the key which is just less than that.. but i thought you guys had a better solution than this also.. but i think i have better than yours – Sushant Kochar Feb 5 '12 at 10:15
    
And to find the maximal key in the array which is less than the key you're about to insert, you'll need to....sort! (At the very least, that's what's going on behind the scenes...) – user554546 Feb 5 '12 at 22:36
1  
I think what the OP is looking for is a data structure in PHP that sorts the array as the items are inserted (in the manner of a binary tree like std::map does in C++). To my knowledge there is no such data structure for a PHP array but you could create it ... whether it would be faster than just filling the array and then sorting it, I don't know. – jdavidbakr Apr 13 '15 at 15:15

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.