Question

Union-Find Show the contents of the id[ ] array and the number of times array is...

Union-Find

Show the contents of the id[ ] array and the number of times array is accessed for each input pair when you that from the of the following sequence of instructions: union(1,2), union(3,4), union(1,7), union(3,6), union(8,9), union(1,8), union(3,10), union(3,11), union(3,12), union(3,13), union(14,15), union(16,0), union(14,16), union(1,3), union(1,14) when the union are

a. Quick-find
b. Quick-union
c. Weighted quick-union

0 0
Add a comment Improve this question Transcribed image text
Answer #1

public class Weight

{

private int[] id;

private int[] size;

private int c;

private int array = 0;

public Weight(int N)

{

c = N;

id = new int[N];

for (int a = 0; a < N; a++){

id[a] = a;

}

  

size = new int[N];

for (int a = 0; a < N; a++)

size[a] = 1;

}

public int c()

{

return c;

}

public boolean join(int m, int n)

{

return find(m) == find(n);

}

private int find(int m)

{

while (m != id[m]) m = id[m];

return m;

}

public void un(int m, int n)

{

System.out.println(" union for " + m + "-" + n);

int a = find(m);

int j = find(n);

if (a == j) return;

if (size[a] < size[j])

{

id[a] = j; size[j] += size[a];

}

else

{

id[j] = a; size[a] += size[j];

}

array++;

for (int k = 0; k < 20; k++){

System.out.printf("%d ", id[k]);

}

System.out.println("");  

c--;

}

public static void main(String args[])

{

Weight wqu = new Weight(20);

wqu.un(1, 2);

wqu.un(3, 4);

wqu.un(1, 7);

wqu.un(3, 6);

wqu.un(8, 9);

wqu.un(1, 8);

wqu.un(3, 10);

wqu.un(3, 11);

wqu.un(3, 12);

wqu.un(3, 13);

wqu.un(14, 15);

wqu.un(16, 0);

wqu.un(14, 16);

wqu.un(1, 3);

wqu.un(1, 14);

System.out.println("Number of Array was accessed " + wqu.array + " times.");

System.out.println("Final ID Array is : ");

for (int a = 0; a < 20; a++){

System.out.println("[" + a +"]:"+wqu.id[a]);

}

}

}

Add a comment
Know the answer?
Add Answer to:
Union-Find Show the contents of the id[ ] array and the number of times array is...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT