libFirm 1.20
libfirm/adt/unionfind.h
Go to the documentation of this file.
00001 /*
00002  * Copyright (C) 1995-2008 University of Karlsruhe.  All right reserved.
00003  *
00004  * This file is part of libFirm.
00005  *
00006  * This file may be distributed and/or modified under the terms of the
00007  * GNU General Public License version 2 as published by the Free Software
00008  * Foundation and appearing in the file LICENSE.GPL included in the
00009  * packaging of this file.
00010  *
00011  * Licensees holding valid libFirm Professional Edition licenses may use
00012  * this file in accordance with the libFirm Commercial License.
00013  * Agreement provided with the Software.
00014  *
00015  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
00016  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
00017  * PURPOSE.
00018  */
00019 
00025 #ifndef FIRM_ADT_UNIONFIND_H
00026 #define FIRM_ADT_UNIONFIND_H
00027 
00028 #include <assert.h>
00029 
00030 #include "../begin.h"
00031 
00049 static inline void uf_init(int* data, size_t n_elems)
00050 {
00051     size_t i;
00052     for(i = 0; i < n_elems; ++i) {
00053         data[i] = -1;
00054     }
00055 }
00056 
00066 static inline int uf_union(int* data, int set1, int set2)
00067 {
00068     int d1;
00069     int d2;
00070     int newcount;
00071 
00072     if(set1 == set2)
00073         return set1;
00074 
00075     /* need 2 set representatives */
00076     d1 = data[set1];
00077     d2 = data[set2];
00078     assert(d1 < 0 && d2 < 0);
00079 
00080     newcount = d1 + d2;
00081     if(d1 > d2) {
00082         data[set1] = set2;
00083         data[set2] = newcount;
00084         return set2;
00085     } else {
00086         data[set2] = set1;
00087         data[set1] = newcount;
00088         return set1;
00089     }
00090 }
00091 
00102 static inline int uf_find(int* data, int e)
00103 {
00104     /* go through list to find representative */
00105     int repr = e;
00106     while(data[repr] >= 0) {
00107         repr = data[repr];
00108     }
00109 
00110     /* update list to point to new representative (path compression) */
00111     while(e != repr) {
00112         int next = data[e];
00113         data[e] = repr;
00114         e = next;
00115     }
00116 
00117     return repr;
00118 }
00119 
00122 #include "../end.h"
00123 
00124 #endif