Skip to content

Commit 47958fb

Browse files
committed
fix lgtm error and add basic docs
1 parent d1dfde4 commit 47958fb

File tree

1 file changed

+56
-13
lines changed

1 file changed

+56
-13
lines changed

misc/union_find.c

Lines changed: 56 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,89 @@
1+
/**
2+
* @file union_find.c
3+
* @brief [Union
4+
* find](https://en.wikipedia.org/wiki/Disjoint-set_data_structure) algorithm.
5+
*/
16
#include <stdio.h>
7+
#include <stdlib.h>
8+
#define MAX_SIZE 1000 /**< maximum number of elements in the set */
29

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)
518
{
19+
if (x >= MAX_SIZE)
20+
{
21+
fprintf(stderr, "Out-of bounds value\n");
22+
exit(EXIT_FAILURE);
23+
}
24+
625
if (p[x] == x)
726
{
827
return x;
928
}
1029
else
1130
{
12-
p[x] = find(p[x]);
31+
p[x] = find(p, p[x]);
1332
return p[x];
1433
}
1534
}
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); }
1835

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 */
1945
int main()
2046
{
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
2250
for (int i = 0; i < 10; i++)
2351
{
24-
p[i] = i;
52+
union_set[i] = i;
2553
}
2654
// 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");
2863
// Now 3 and 5 are groupped together, that is find(3) = find(5)
2964
// 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+
3174
// Now 3, 5 and are groupped together, find(3) = find(5) = find(8)
3275
// 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))
3578
{
3679
printf("0 and 3 are groupped together\n");
3780
}
3881
printf("The array is now: ");
3982
for (int i = 0; i < 10; i++)
4083
{
41-
printf("%d ", p[i]);
84+
printf("%d ", union_set[i]);
4285
}
4386
printf("\n");
4487

4588
return 0;
46-
}
89+
}

0 commit comments

Comments
 (0)