private void orderedInsert(int oid, double dist){
            double rdist=0;
            if(orderedRes.size()<=k){
                intWrapper o=new intWrapper();
                o.value=oid;
                doubleWrapper d=eliminateDuplicateObjects(objectsOfOrderedRes,o);  // if it is already there we remove it
                if (d!=null)
                    eliminateDuplicateDistances(orderedRes,d);
                else
                    d=new doubleWrapper();
                while(o!=null)
                {
                    orderedInsertions++;
                    dist+=rdist;
                    d.value=dist;
                    objectsOfOrderedRes.put(o,d);
                    o=orderedRes.put(d,o);           //there could be another object with the same distance: we have to reinsrt it
                    rdist+=0.0001*Math.random();
                    if(o!=null)
                        d=new doubleWrapper();
                }
                kDist=orderedRes.lastKey().value;
            }
            else if(dist<kDist)
            {
                intWrapper o=new intWrapper();
                o.value=oid;
                doubleWrapper d=eliminateDuplicateObjects(objectsOfOrderedRes,o);  // if it is already there we remove it
                if (d!=null)
                    eliminateDuplicateDistances(orderedRes,d);
                if(orderedRes.size()>=k-1){
                    intWrapper to=orderedRes.remove(orderedRes.lastKey());  
                    d= objectsOfOrderedRes.remove(to);
                }
                while(o!=null)
                {
                    orderedInsertions++;
                    dist+=rdist;
                    d.value=dist;
                    objectsOfOrderedRes.put(o,d);
                    o=orderedRes.put(d,o);        //there could be another object with the same distance: we have to reinsrt it
                    rdist+=0.0001*Math.random();
                    if(o!=null)
                        d=new doubleWrapper();
                }
                kDist=orderedRes.lastKey().value;
            }
        }