0

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.

2
  • 2
    So you want the array sorted, without sorting it? Good luck with that. Commented Feb 5, 2012 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) Commented Feb 5, 2012 at 10:11

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.