Cosmetic changes
[libfirm] / ir / adt / unionfind.h
1 /*
2  * Project:     libFIRM
3  * File name:   ir/adt/unionfind.h
4  * Purpose:     Union-Find datastructure
5  * Author:      Matthias Braun
6  * Modified by:
7  * CVS-ID:      $Id$
8  * Copyright:   (c) 2006, Matthias Braun
9  * Licence:     This file protected by GPL -  GNU GENERAL PUBLIC LICENSE.
10  */
11
12 /**
13  * @file unionfind.h
14  *
15  * Union-Find datastructure
16  */
17 #ifndef _UNIONFIND_H
18 #define _UNIONFIND_H
19
20 #include <assert.h>
21
22 /**
23  * Call this to initialize an array of @p count elements to be used by the
24  * union find functions.
25  *
26  * @param data  The array (you have to allocate it yourself)
27  * @param from  The first element that should be intialized
28  * @param to    the index of the first element which is not initialized anymore
29  */
30 static INLINE void uf_init(int* data, int from, int to)
31 {
32         int i;
33         for(i = from; i < to; ++i) {
34                 data[i] = -1;
35         }
36 }
37
38 /**
39  * Merge 2 sets (union operation). Note that you have to pass the
40  * representatives of the sets and not just random elements
41  *
42  * @param data  The union find data
43  * @param set1  Representative of set1
44  * @param set2  Representative of set2
45  * @return              0 if the new union set is represented by set1, 1 if it is
46  *              represented by set2
47  */
48 static INLINE int uf_union(int* data, int set1, int set2) {
49         int d1 = data[set1];
50         int d2 = data[set2];
51         int newcount;
52
53         if(set1 == set2)
54                 return 0;
55
56         // need 2 set represantatives
57         assert(d1 < 0 && d2 < 0);
58
59         newcount = d1 + d2;
60         if(d1 > d2) {
61                 data[set1] = set2;
62                 data[set2] = newcount;
63                 return 1;
64         } else {
65                 data[set2] = set1;
66                 data[set1] = newcount;
67                 return 0;
68         }
69 }
70
71 /**
72  * Finds the representative for the set with member @p e.
73  * The representative of a set is unique, so if the find operations
74  * 2 similar/different representatives, then the elements are in the
75  * same/2 different sets.
76  *
77  * @param data  The union find data
78  * @param e             The element
79  * @return              The representative of the set that contains @p e
80  */
81 static INLINE int uf_find(int* data, int e) {
82         // go through list to find representative
83     int repr = e;
84         while(data[repr] >= 0) {
85                 repr = data[repr];
86         }
87
88         // update list to point to new representative (path compression)
89         while(e != repr) {
90                 int next = data[e];
91                 data[e] = repr;
92                 e = next;
93         }
94
95         return repr;
96 }
97
98 #endif