[GRASS-SVN] r64659 - grass/trunk/vector/v.to.db

svn_grass at osgeo.org svn_grass at osgeo.org
Tue Feb 17 02:48:36 PST 2015


Author: mmetz
Date: 2015-02-17 02:48:36 -0800 (Tue, 17 Feb 2015)
New Revision: 64659

Modified:
   grass/trunk/vector/v.to.db/find.c
Log:
v.to.db: bsearch cat

Modified: grass/trunk/vector/v.to.db/find.c
===================================================================
--- grass/trunk/vector/v.to.db/find.c	2015-02-16 20:05:05 UTC (rev 64658)
+++ grass/trunk/vector/v.to.db/find.c	2015-02-17 10:48:36 UTC (rev 64659)
@@ -2,30 +2,73 @@
 #include <string.h>
 #include  "global.h"
 
+
+static int bsearch_cat(int cat)
+{
+    int mid, lo, hi;
+    
+    if (vstat.rcat < 1)
+	return -1;
+
+    lo = 0;
+    hi = vstat.rcat - 1;
+    
+    if (hi == 0 || Values[lo].cat > cat || Values[hi].cat < cat)
+	return -1;
+
+    if (Values[hi].cat == cat)
+	return hi;
+
+    if (Values[lo].cat == cat)
+	return lo;
+
+    while (lo < hi) {
+	mid = (lo + hi) / 2;
+	
+	if (Values[mid].cat == cat)
+	    return mid;
+
+	if (Values[mid].cat > cat) {
+	    hi = mid;
+	}
+	else {
+	    lo = mid;
+	}
+    }
+    
+    return -1;
+}
+
 /* returns index to array of values, inserts new if necessary */
 int find_cat(int cat, int add)
 {
     int i;
 
-    for (i = 0; i < vstat.rcat; i++)
-	if (Values[i].cat == cat)
+    if ((i = bsearch_cat(cat)) >= 0)
 	    return i;
 
     if (!add)
 	return -1;
 
     /* Not found -> add new */
-    Values[vstat.rcat].cat = cat;
-    Values[vstat.rcat].count1 = 0;
-    Values[vstat.rcat].count1 = 0;
-    Values[vstat.rcat].i1 = -1;
-    Values[vstat.rcat].i2 = -1;
-    Values[vstat.rcat].d1 = 0.0;
-    Values[vstat.rcat].d2 = 0.0;
-    Values[vstat.rcat].qcat = NULL;
-    Values[vstat.rcat].nqcats = 0;
-    Values[vstat.rcat].aqcats = 0;
+    for (i = vstat.rcat; i > 0; i--) {
+	if (Values[i - 1].cat < cat)
+	    break;
+
+	Values[i] = Values[i - 1];
+    }
+    Values[i].cat = cat;
+    Values[i].count1 = 0;
+    Values[i].count1 = 0;
+    Values[i].i1 = -1;
+    Values[i].i2 = -1;
+    Values[i].d1 = 0.0;
+    Values[i].d2 = 0.0;
+    Values[i].qcat = NULL;
+    Values[i].nqcats = 0;
+    Values[i].aqcats = 0;
+
     vstat.rcat++;
 
-    return (vstat.rcat - 1);
+    return (i);
 }



More information about the grass-commit mailing list