title: Can we have an if loop for the root section of Quick Union algorithm?
body: <p>In the Quick Union algorithm imlementation below, inside the root method can we have an if loop (such as if(i != id[i]) instead of the while loop? I think it works just as well. Then why did they use the while loop?</p>
  
  <pre><code>public class QuickUnionUF {
      private int []id;
  
      public QuickUnionUF(int N){
          id = new int[N];
          for(int i=0; i&lt;N; i++) id[i] = i;
      }
  
      private int root(int i){
          while(i != id[i]) i = id[i];
          return i;
      }
  
      public boolean connected(int p, int q){
          return root(p) == root(q);
      }
  
      public void union(int p, int q){
          int i = root(p);
          int j = root(q);
          id[i] = j;
      }
  }
  </code></pre>