Algorithms_in_C 1.0.0
Set of algorithms implemented in C.
Loading...
Searching...
No Matches
union_find.c File Reference

Union find algorithm. More...

#include <stdio.h>
#include <stdlib.h>
Include dependency graph for union_find.c:

Macros

#define MAX_SIZE   1000
 maximum number of elements in the set
 

Functions

int find (int *p, int x)
 Find index of or value in an array. More...
 
void join (int *p, int x, int y)
 Function to join. More...
 
int main ()
 Main function. More...
 

Detailed Description

Union find algorithm.

Function Documentation

◆ find()

int find ( int *  p,
int  x 
)

Find index of or value in an array.

Parameters
[in,out]parray to search and update
xvalue to search
Returns
value at the index x
18{
19 if (x >= MAX_SIZE)
20 {
21 fprintf(stderr, "Out-of bounds value\n");
22 exit(EXIT_FAILURE);
23 }
24
25 if (p[x] == x)
26 {
27 return x;
28 }
29 else
30 {
31 p[x] = find(p, p[x]);
32 return p[x];
33 }
34}
#define MAX_SIZE
maximum number of elements in the set
Definition: union_find.c:8
int find(int *p, int x)
Find index of or value in an array.
Definition: union_find.c:17
Here is the call graph for this function:

◆ join()

void join ( int *  p,
int  x,
int  y 
)

Function to join.

Parameters
[in,out]parray to join in
xvalue or index to join to
yvalue or index to join from
42{ p[find(p, x)] = find(p, y); }
Here is the call graph for this function:

◆ main()

int main ( void  )

Main function.

46{
47 int union_set[MAX_SIZE];
48
49 // Have all array indexes that you need to use reference themselves
50 for (int i = 0; i < 10; i++)
51 {
52 union_set[i] = i;
53 }
54 // p = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
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");
63 // Now 3 and 5 are groupped together, that is find(3) = find(5)
64 // p = {0, 1, 2, 5, 4, 5, 6, 7, 8, 9}
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
74 // Now 3, 5 and are groupped together, find(3) = find(5) = find(8)
75 // p = {0, 1, 2, 5, 4, 8, 6, 7, 8, 9}
76 join(union_set, 0, 5);
77 if (find(union_set, 0) == find(union_set, 3))
78 {
79 printf("0 and 3 are groupped together\n");
80 }
81 printf("The array is now: ");
82 for (int i = 0; i < 10; i++)
83 {
84 printf("%d ", union_set[i]);
85 }
86 printf("\n");
87
88 return 0;
89}
void join(int *p, int x, int y)
Function to join.
Definition: union_find.c:42
Here is the call graph for this function: