1
+ /**
2
+ * @file union_find.c
3
+ * @brief [Union
4
+ * find](https://en.wikipedia.org/wiki/Disjoint-set_data_structure) algorithm.
5
+ */
1
6
#include <stdio.h>
7
+ #include <stdlib.h>
8
+ #define MAX_SIZE 1000 /**< maximum number of elements in the set */
2
9
3
- int p [1000000 ];
4
- int find (int x )
10
+ /**
11
+ * @brief Find index of or value in an array
12
+ *
13
+ * @param [in,out] p array to search and update
14
+ * @param x value to search
15
+ * @return value at the index `x`
16
+ */
17
+ int find (int * p , int x )
5
18
{
19
+ if (x >= MAX_SIZE )
20
+ {
21
+ fprintf (stderr , "Out-of bounds value\n" );
22
+ exit (EXIT_FAILURE );
23
+ }
24
+
6
25
if (p [x ] == x )
7
26
{
8
27
return x ;
9
28
}
10
29
else
11
30
{
12
- p [x ] = find (p [x ]);
31
+ p [x ] = find (p , p [x ]);
13
32
return p [x ];
14
33
}
15
34
}
16
- // Call to function join(int x, int y) to join PARAM x and y
17
- void join (int x , int y ) { p [find (x )] = find (y ); }
18
35
36
+ /**
37
+ * @brief Function to join
38
+ * @param [in,out] p array to join in
39
+ * @param x value or index to join to
40
+ * @param y value or index to join from
41
+ */
42
+ void join (int * p , int x , int y ) { p [find (p , x )] = find (p , y ); }
43
+
44
+ /** Main function */
19
45
int main ()
20
46
{
21
- // Have all array indexes that you need to use refrence themselves
47
+ int union_set [MAX_SIZE ];
48
+
49
+ // Have all array indexes that you need to use reference themselves
22
50
for (int i = 0 ; i < 10 ; i ++ )
23
51
{
24
- p [i ] = i ;
52
+ union_set [i ] = i ;
25
53
}
26
54
// p = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
27
- join (3 , 5 );
55
+
56
+ join (union_set , 3 , 5 );
57
+ printf ("The array is now: " );
58
+ for (int i = 0 ; i < 10 ; i ++ )
59
+ {
60
+ printf ("%d " , union_set [i ]);
61
+ }
62
+ printf ("\n" );
28
63
// Now 3 and 5 are groupped together, that is find(3) = find(5)
29
64
// p = {0, 1, 2, 5, 4, 5, 6, 7, 8, 9}
30
- join (3 , 8 );
65
+
66
+ join (union_set , 3 , 8 );
67
+ printf ("The array is now: " );
68
+ for (int i = 0 ; i < 10 ; i ++ )
69
+ {
70
+ printf ("%d " , union_set [i ]);
71
+ }
72
+ printf ("\n" );
73
+
31
74
// Now 3, 5 and are groupped together, find(3) = find(5) = find(8)
32
75
// p = {0, 1, 2, 5, 4, 8, 6, 7, 8, 9}
33
- join (0 , 5 );
34
- if (find (0 ) == find (3 ))
76
+ join (union_set , 0 , 5 );
77
+ if (find (union_set , 0 ) == find (union_set , 3 ))
35
78
{
36
79
printf ("0 and 3 are groupped together\n" );
37
80
}
38
81
printf ("The array is now: " );
39
82
for (int i = 0 ; i < 10 ; i ++ )
40
83
{
41
- printf ("%d " , p [i ]);
84
+ printf ("%d " , union_set [i ]);
42
85
}
43
86
printf ("\n" );
44
87
45
88
return 0 ;
46
- }
89
+ }
0 commit comments