|
| 1 | +#include <stdio.h> |
| 2 | +#include <stdlib.h> |
| 3 | +int find(int a, int parent[]) // recursive function to find parent of a |
| 4 | +{ |
| 5 | + if (parent[a] == a) // if root itself is a parent |
| 6 | + return a; |
| 7 | + else |
| 8 | + return find(parent[a], parent); // to find the parent of the parent |
| 9 | +} |
| 10 | + |
| 11 | +void unionn(int a, int b, int parent[], int rank[]) // function to do unionn of a and b |
| 12 | +{ |
| 13 | + int a1 = find(a, parent); // to find parent of a |
| 14 | + int b1 = find(b, parent); // to find parent of b |
| 15 | + if (a1 == b1) // if both have same parent that is both are in same set |
| 16 | + { |
| 17 | + printf("both the elements are in same set\n"); |
| 18 | + return; |
| 19 | + } |
| 20 | + if (rank[a1] > rank[b1]) // if height of parent of a is greater than height of parent of b |
| 21 | + { |
| 22 | + parent[b1] = a1; |
| 23 | + } |
| 24 | + else if (rank[a1] < rank[b1]) // if height of parent of b is greater than height of parent of a |
| 25 | + { |
| 26 | + parent[a1] = b1; |
| 27 | + } |
| 28 | + else // if height of both parent is same |
| 29 | + { |
| 30 | + parent[a1] = b1; |
| 31 | + rank[b1]++; |
| 32 | + } |
| 33 | +} |
| 34 | +int main() |
| 35 | +{ |
| 36 | + int n = 10; |
| 37 | + int parent[n]; |
| 38 | + int rank[n]; |
| 39 | + |
| 40 | + for (int i = 0; i < 10; i++) |
| 41 | + parent[i] = i; // in starting the node is itself the parent |
| 42 | + for (int i = 0; i < 10; i++) |
| 43 | + rank[i] = 1; // by default the rank of all nodes is 1 |
| 44 | + |
| 45 | + unionn(3, 8, parent, rank); // 3 is friend of 8 |
| 46 | + unionn(3, 6, parent, rank); // 3 is friend of 6 |
| 47 | + printf("the parent of 8 is %d\n", find(8, parent)); |
| 48 | + |
| 49 | + unionn(1, 9, parent, rank); // 1 is friend of 9 |
| 50 | + unionn(2, 8, parent, rank); // 2 is friend of 8 |
| 51 | + unionn(5, 8, parent, rank); // 5 is friend of 8 |
| 52 | + |
| 53 | + unionn(2, 9, parent, rank); // 2 is friend of 9 |
| 54 | + printf("the parent of 2 is %d\n", find(2, parent)); |
| 55 | + printf("the parent of 8 is%d\n", find(8, parent)); |
| 56 | + |
| 57 | + if (find(5, parent) == find(7, parent)) // to check whether 5 is friend of 7 or not |
| 58 | + printf("5 is a friend of 7\n"); |
| 59 | + else |
| 60 | + printf("5 is not a friend of 7\n"); |
| 61 | + if (find(3, parent) == find(1, parent)) // to check whether 3 is friend of 1 or not |
| 62 | + printf("3 is a friend of 1\n"); |
| 63 | + else |
| 64 | + printf("3 is not a friend of 1\n"); |
| 65 | + |
| 66 | + return 0; |
| 67 | +} |
0 commit comments