ChartSampleSearch { static public int findClosestSample(ChartSampleSequence samples, double x) { synchronized (samples) { ChartSampleSearch binary = new ChartSampleSearch(); if (binary.search(samples, x)) return binary.mid; if (binary.cmp > 0) { if (binary.mid > 0 && (x - samples.get(binary.mid-1).getX() < samples.get(binary.mid).getX() - x)) return binary.mid-1; return binary.mid; } if (binary.mid+1 < samples.size() && (samples.get(binary.mid+1).getX() - x < x - samples.get(binary.mid).getX())) return binary.mid+1; return binary.mid; } }  static int findSampleLessOrEqual(ChartSampleSequence samples, double x); static int findSampleGreaterOrEqual(ChartSampleSequence samples, double x); static int findClosestSample(ChartSampleSequence samples, double x);  }
@Test public void testFindClosest() throws Exception { double x; int i; x = 4.0; i = ChartSampleSearch.findClosestSample(samples, x); assertTrue(i >= 0); assertTrue(i < samples.size()); assertTrue(samples.get(i).getX() == x); assertEquals(1, i); i = ChartSampleSearch.findClosestSample(samples, 4.1); assertEquals(1, i); i = ChartSampleSearch.findClosestSample(samples, 4.4); assertEquals(1, i); i = ChartSampleSearch.findClosestSample(samples, 5.2); assertEquals(2, i); i = ChartSampleSearch.findClosestSample(samples, 6.0); assertEquals(2, i); i = ChartSampleSearch.findClosestSample(samples, 6.9); assertEquals(2, i); i = ChartSampleSearch.findClosestSample(samples, 2.0); assertEquals(0, i); i = ChartSampleSearch.findClosestSample(samples, 1.0); assertEquals(0, i); i = ChartSampleSearch.findClosestSample(samples, -2.0); assertEquals(0, i); i = ChartSampleSearch.findClosestSample(samples, 17.8); assertEquals(8, i); i = ChartSampleSearch.findClosestSample(samples, 18.0); assertEquals(8, i); i = ChartSampleSearch.findClosestSample(samples, 200.0); assertEquals(8, i); }