about summary refs log tree commit diff
path: root/usth/ICT2.2/midterm/src/Search.java
diff options
context:
space:
mode:
authorNguyễn Gia Phong <vn.mcsinyx@gmail.com>2019-12-15 10:34:58 +0700
committerNguyễn Gia Phong <vn.mcsinyx@gmail.com>2019-12-15 15:00:00 +0700
commit67393f42f41ab92219deb549f711121c4dab845b (patch)
treeebd0eb6c8a3d3bd69937312179aeaf273ea29c80 /usth/ICT2.2/midterm/src/Search.java
parentb38d9929f7a015b56b847fde7e83f814f354497e (diff)
downloadcp-67393f42f41ab92219deb549f711121c4dab845b.tar.gz
[usth/ICT2.2] Object Oriented Programming
Diffstat (limited to 'usth/ICT2.2/midterm/src/Search.java')
-rw-r--r--usth/ICT2.2/midterm/src/Search.java57
1 files changed, 57 insertions, 0 deletions
diff --git a/usth/ICT2.2/midterm/src/Search.java b/usth/ICT2.2/midterm/src/Search.java
new file mode 100644
index 0000000..efb9e45
--- /dev/null
+++ b/usth/ICT2.2/midterm/src/Search.java
@@ -0,0 +1,57 @@
+import java.util.List;
+import java.util.Comparator;
+
+public class Search
+{
+  public static final int NOT_FOUND = -1;
+
+  public static int linear(List list, Object key)
+  {
+    for (int i = 0; i < list.size(); ++i)
+      if (key == null ? list.get(i) == null : key.equals(list.get(i)))
+        return i;
+    return NOT_FOUND;
+  }
+
+  private static <T>
+  int binary(List<? extends Comparable<? super T>> list, T key,
+             int low, int high)
+  {
+    if (high < low)
+      return NOT_FOUND;
+    var mid = (low + high) / 2;
+    var cmp = list.get(mid).compareTo(key);
+    if (cmp < 0)
+      return binary(list, key, mid + 1, high);
+    if (cmp > 0)
+      return binary(list, key, low, mid - 1);
+    return mid;
+  }
+
+  public static <T>
+  int binary(List<? extends Comparable<? super T>> list, T key)
+  {
+    return binary(list, key, 0, list.size());
+  }
+
+  private static <T>
+  int binary(List<? extends T> list, T key, Comparator<? super T> c,
+             int low, int high)
+  {
+    if (high < low)
+      return NOT_FOUND;
+    var mid = (low + high) / 2;
+    var cmp = c.compare(list.get(mid), key);
+    if (cmp < 0)
+      return binary(list, key, c, mid + 1, high);
+    if (cmp > 0)
+      return binary(list, key, c, low, mid - 1);
+    return mid;
+  }
+
+  public static <T>
+  int binary(List<? extends T> list, T key, Comparator<? super T> c)
+  {
+    return binary(list, key, c, 0, list.size());
+  }
+}