2015-08-16 2 views
1
public class WeightedQuickUnionUF { 
    private int[] id; 
    private int[] sz; 

    public WeightedQuickUnionUF(int N){ 
     id = new int[N]; 
     sz = new int[N]; 
     for(int i=0;i<N;i++) 
      id[i] = i; 
     for(int j=0;j<N;j++) 
      sz[j] = 1; 
    } 

    // find the root of that number 
    public int root(int p){ 
     while(p != id[p]) 
      // // Follow links to find a root. 
      p = id[p]; 
     return p; 
    } 

    public int getid(int p){ 
     return id[p]; 
    } 
    public int getsize(int p){ 
     return sz[p]; 
    } 

    // print the array 
    // I use 2 ways to print the final array, but the results are different 
    public void show(){ 
     for(int ele:id) 
      System.out.print(id[ele]+ " "); 
     for(int j=0;j<id.length;j++) 
      System.out.print(id[j]+ " "); 
     System.out.print("\n"); 
    } 
    // link two trees, the root of the smaller one will be linked to the 
    // root of the larger one 
    public void union(int p, int q){ 
     int rootp = root(p); 
     int rootq = root(q); 
     if(sz[rootp] < sz[rootq]){ 
      id[rootp] = rootq; 
      sz[rootq] += sz[rootp]; 
     } 
     else{ 
      id[rootq] = rootp; 
      sz[rootp] += sz[rootq]; 
     } 
    } 
    // test the class I have defined 
    public static void main(String args[]){ 
     WeightedQuickUnionUF test1 = new WeightedQuickUnionUF(10); 
     test1.union(6, 0); 
     test1.union(1, 7); 
     test1.union(7, 9); 
     test1.union(8, 9); 
     test1.union(8, 5); 
     test1.union(4, 2); 
     test1.union(9, 3); 
     test1.union(4, 0); 
     test1.union(3, 0); 
     test1.show(); 
    } 
} 

Моя проблема связана с производительностью функции show(). Я использую 2 метода для печати одного и того же массива, но результаты разные. Правильный вывод этого кода должен быть 6 1 4 1 1 1 4 1 1 1, что означает, что цикл for может дать мне правильный ответ. Но для каждого цикла просто не может поступать правильно.Разница между циклами и для каждого цикла при наборе массива

+2

Используйте только 'ele' вместо' ид [Эле] ' –

ответ

3

for-each loop не ведет себя так, как будто вы ожидаете. То есть,

for(int ele : id) 
    System.out.print(id[ele]+ " "); 

должно быть что-то вроде (и я рекомендую использовать фигурные скобки)

for (int ele : id) { 
    System.out.print(ele + " "); 
} 
Смежные вопросы