1 | using System;
|
---|
2 | using System.Collections.Generic;
|
---|
3 | using System.Linq;
|
---|
4 | using System.Text;
|
---|
5 | using System.Windows;
|
---|
6 |
|
---|
7 | namespace Microsoft.Research.DynamicDataDisplay.Common.DataSearch
|
---|
8 | {
|
---|
9 | internal class SortedXSearcher1d
|
---|
10 | {
|
---|
11 | private readonly IList<Point> collection;
|
---|
12 | public SortedXSearcher1d(IList<Point> collection)
|
---|
13 | {
|
---|
14 | if (collection == null)
|
---|
15 | throw new ArgumentNullException("collection");
|
---|
16 |
|
---|
17 | this.collection = collection;
|
---|
18 | }
|
---|
19 |
|
---|
20 | public SearchResult1d SearchXBetween(double x)
|
---|
21 | {
|
---|
22 | return SearchXBetween(x, SearchResult1d.Empty);
|
---|
23 | }
|
---|
24 |
|
---|
25 | public SearchResult1d SearchXBetween(double x, SearchResult1d result)
|
---|
26 | {
|
---|
27 | if (collection.Count == 0)
|
---|
28 | return SearchResult1d.Empty;
|
---|
29 |
|
---|
30 | int lastIndex = collection.Count - 1;
|
---|
31 |
|
---|
32 | if (x < collection[0].X)
|
---|
33 | return SearchResult1d.Empty;
|
---|
34 | else if (collection[lastIndex].X < x)
|
---|
35 | return SearchResult1d.Empty;
|
---|
36 |
|
---|
37 | int startIndex = !result.IsEmpty ? Math.Min(result.Index, lastIndex) : 0;
|
---|
38 |
|
---|
39 | // searching ascending
|
---|
40 | if (collection[startIndex].X < x)
|
---|
41 | {
|
---|
42 | for (int i = startIndex + 1; i <= lastIndex; i++)
|
---|
43 | if (collection[i].X >= x)
|
---|
44 | return new SearchResult1d { Index = i - 1 };
|
---|
45 | }
|
---|
46 | else // searching descending
|
---|
47 | {
|
---|
48 | for (int i = startIndex - 1; i >= 0; i--)
|
---|
49 | if (collection[i].X <= x)
|
---|
50 | return new SearchResult1d { Index = i };
|
---|
51 | }
|
---|
52 |
|
---|
53 | throw new InvalidOperationException("Should not appear here.");
|
---|
54 | }
|
---|
55 | }
|
---|
56 | }
|
---|