22990f6db1fd50a363e8befddf25e9f55f03c3c2
[jalview.git] / src2 / intervalstore / impl / BinarySearcher.java
1 /*
2 BSD 3-Clause License
3
4 Copyright (c) 2018, Mungo Carstairs
5 All rights reserved.
6
7 Redistribution and use in source and binary forms, with or without
8 modification, are permitted provided that the following conditions are met:
9
10 * Redistributions of source code must retain the above copyright notice, this
11   list of conditions and the following disclaimer.
12
13 * Redistributions in binary form must reproduce the above copyright notice,
14   this list of conditions and the following disclaimer in the documentation
15   and/or other materials provided with the distribution.
16
17 * Neither the name of the copyright holder nor the names of its
18   contributors may be used to endorse or promote products derived from
19   this software without specific prior written permission.
20
21 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
22 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
24 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
25 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
27 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
28 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 */
32 package intervalstore.impl;
33
34 import java.util.List;
35
36 import intervalstore.api.IntervalI;
37
38 /**
39  * Provides a method to perform binary search of an ordered list of
40  * {@code IntervalI} objects for the first entry that satisfies a supplied
41  * condition on either the begin or end value of the intervals
42  * 
43  * @author gmcarstairs
44  */
45 public final class BinarySearcher
46 {
47   /*
48    * compare using <, <=, =, >=, >
49    */
50   public enum Compare
51   {
52     LT, LE, EQ, GE, GT
53   }
54
55   private BinarySearcher()
56   {
57   }
58
59   /**
60    * Performs a binary search of the list to find the index of the first entry
61    * for which the test returns true. Answers the length of the list if there is
62    * no such entry.
63    * <p>
64    * For correct behaviour, the provided list must be ordered consistent with
65    * the test, that is, any entries returning false must precede any entries
66    * returning true. Note that this means that this method is <em>not</em>
67    * usable to search for equality (to find a specific entry), as all unequal
68    * entries will answer false to the test. To do that, use
69    * <code>Collections.binarySearch</code> instead.
70    * 
71    * @param list
72    *          the list to be searched
73    * @param compareValue
74    *          a function that extracts the value to be compared from an entry
75    * @param compareTo
76    *          the value to compare to
77    * @param test
78    *          a function that compares (compareValue, compareTo) and returns
79    *          true or false
80    * @return
81    * @see java.util.Collections#binarySearch(List, Object)
82    */
83   public static int findFirst(List<? extends IntervalI> list,
84           boolean compareBegin,
85           Compare comp, int compareto)
86   {
87     int start = 0;
88     int matched = list.size();
89     int end = matched - 1;
90   
91     /*
92      * shortcut for the case that the last entry in the list
93      * fails the test (this arises when adding non-overlapping
94      * intervals in ascending start position order) 
95      */
96     if (end > 0)
97     {
98       IntervalI last = list.get(end);
99       if (!compare(last, compareBegin, comp, compareto))
100       {
101         return matched;
102       }
103     }
104
105     while (start <= end)
106     {
107       int mid = (start + end) / 2;
108       IntervalI entry = list.get(mid);
109       if (compare(entry, compareBegin, comp, compareto))
110       {
111         matched = mid;
112         end = mid - 1;
113       }
114       else
115       {
116         start = mid + 1;
117       }
118     }
119   
120     return matched;
121   }
122
123   /**
124    * Applies the comparison specified by {@code comp} to either the
125    * {@code begin} value of {@code entry} (if {@code compareBegin} is true) or
126    * the {@code end} value, and the {@code compareTo} value, and returns the
127    * result of the comparison
128    * 
129    * @param entry
130    * @param compareBegin
131    * @param comp
132    * @param compareTo
133    * @return
134    */
135   private static boolean compare(IntervalI entry, boolean compareBegin,
136           Compare comp, int compareTo)
137   {
138     int val = compareBegin ? entry.getBegin() : entry.getEnd();
139     boolean result;
140     switch (comp)
141     {
142     case LT:
143       result = val < compareTo;
144       break;
145     case LE:
146       result = val <= compareTo;
147       break;
148     case EQ:
149       result = val == compareTo;
150       break;
151     case GE:
152       result = val >= compareTo;
153       break;
154     case GT:
155     default:
156       result = val > compareTo;
157     }
158     return result;
159   }
160 }