libFirm
unionfind.h
1 /*
2  * This file is part of libFirm.
3  * Copyright (C) 2012 University of Karlsruhe.
4  */
5 
11 #ifndef FIRM_ADT_UNIONFIND_H
12 #define FIRM_ADT_UNIONFIND_H
13 
14 #include <assert.h>
15 
16 #include "../begin.h"
17 
35 static inline void uf_init(int *const data, size_t const n_elems)
36 {
37  for (size_t i = 0; i < n_elems; ++i) {
38  data[i] = -1;
39  }
40 }
41 
51 static inline int uf_union(int *const data, int const set1, int const set2)
52 {
53  if (set1 == set2)
54  return set1;
55 
56  /* need 2 set representatives */
57  int const d1 = data[set1];
58  int const d2 = data[set2];
59  assert(d1 < 0 && d2 < 0);
60 
61  int const newcount = d1 + d2;
62  if (d1 > d2) {
63  data[set1] = set2;
64  data[set2] = newcount;
65  return set2;
66  } else {
67  data[set2] = set1;
68  data[set1] = newcount;
69  return set1;
70  }
71 }
72 
83 static inline int uf_find(int *const data, int const e)
84 {
85  /* go through list to find representative */
86  int repr = e;
87  while (data[repr] >= 0) {
88  repr = data[repr];
89  }
90 
91  /* update list to point to new representative (path compression) */
92  int t = e;
93  while (t != repr) {
94  int const next = data[t];
95  data[t] = repr;
96  t = next;
97  }
98 
99  return repr;
100 }
101 
104 #include "../end.h"
105 
106 #endif
static void uf_init(int *const data, size_t const n_elems)
Call this to initialize an array of count elements to be used by the union find functions.
Definition: unionfind.h:35
static int uf_find(int *const data, int const e)
Finds the representative for the set with member e.
Definition: unionfind.h:83
static int uf_union(int *const data, int const set1, int const set2)
Merge 2 sets (union operation).
Definition: unionfind.h:51