0

I'm trying to insert element to quadtree when mouse clicked. I call insert method when mouse clicked and sending point as parameter. After few clicks, while loop in insert method goes infinity and I couldn't find out why.

Here's method;

public void insert(Point point){
        Node newNode = new Node(point);
        if(root==null){
            root=newNode;
            return;
        }
        Node current=root;
        Node parent=null;

        while(true){
            parent = current;
            System.out.println("a");
            if(point.getX()<current.point.getX() && point.getY()<current.point.getY()){
                current=current.NW;
                if(current==null){
                    parent.NW= newNode;
                    return;
                }           
            }
            else if(point.getX()>current.point.getX() && point.getY()<current.point.getY()){
                current=current.NE;
                if(current==null){
                    parent.NE= newNode;
                    return;
                }           
        }
            else if(point.getX()<current.point.getX() && point.getY()>current.point.getY()){
                current=current.SW;
                if(current==null){
                    parent.SW=newNode;
                    return;
                }
            }
            else if(point.getX()>current.point.getX() && point.getY()>current.point.getY()){
                current=current.SE;
                if(current==null){
                    parent.SE=newNode;
                    return;
                }
            }

    }
    }

If you need rest of code, let me know.

nerdicsapo
  • 427
  • 5
  • 16

1 Answers1

1

Well, you haven't covered the cases where point and current.point are the same point, or are in line horizontally, or are in line vertically. In each of these three cases, none of your if conditions are true, and there's no way to exit the loop.

You need to change either your < conditions to <= or your > conditions to >=. So, something like

if(point.getX()<=current.point.getX() && point.getY()<=current.point.getY()){

and similarly for every other comparison you've done using <.

This makes sure that your loop can exit when the X value are equal, or when the Y values are equal.

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110