JAL-98 generalised increment() to add() and made faster
authorgmungoc <g.m.carstairs@dundee.ac.uk>
Mon, 26 Sep 2016 08:21:25 +0000 (09:21 +0100)
committergmungoc <g.m.carstairs@dundee.ac.uk>
Mon, 26 Sep 2016 08:21:25 +0000 (09:21 +0100)
src/jalview/ext/android/SparseIntArray.java

index 0e05803..4ddf776 100644 (file)
@@ -348,21 +348,43 @@ public class SparseIntArray implements Cloneable
   }
 
   /**
-   * Method added for Jalview to increment a key's value if present, else add it
-   * with the value 1
+   * Method (copied from put) added for Jalview to efficiently increment a key's
+   * value if present, else add it with the given value. This avoids a double
+   * binary search (once to get the value, again to put the updated value).
    * 
    * @param key
+   * @oparam toAdd
    */
-  public void increment(int key)
+  public void add(int key, int toAdd)
   {
     int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
     if (i >= 0)
     {
-      mValues[i]++;
+      mValues[i] += toAdd;
     }
     else
     {
-      put(key, 1);
+      i = ~i;
+      if (mSize >= mKeys.length)
+      {
+        int n = idealIntArraySize(mSize + 1);
+        int[] nkeys = new int[n];
+        int[] nvalues = new int[n];
+        // Log.e("SparseIntArray", "grow " + mKeys.length + " to " + n);
+        System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length);
+        System.arraycopy(mValues, 0, nvalues, 0, mValues.length);
+        mKeys = nkeys;
+        mValues = nvalues;
+      }
+      if (mSize - i != 0)
+      {
+        // Log.e("SparseIntArray", "move " + (mSize - i));
+        System.arraycopy(mKeys, i, mKeys, i + 1, mSize - i);
+        System.arraycopy(mValues, i, mValues, i + 1, mSize - i);
+      }
+      mKeys[i] = key;
+      mValues[i] = toAdd;
+      mSize++;
     }
   }
 }