summaryrefslogtreecommitdiff
path: root/Assets/Algorithms/Searching.cs
diff options
context:
space:
mode:
authorchai <chaifix@163.com>2021-06-21 22:59:39 +0800
committerchai <chaifix@163.com>2021-06-21 22:59:39 +0800
commit5d81d8d8b4062def695c27fa02f67625871e8dce (patch)
tree1ab1a4b48b029e5f84d73cf0a6e7140782eb27e9 /Assets/Algorithms/Searching.cs
parentcc475a8b16b0e9323623c6532e114dceeb64353a (diff)
*misc
Diffstat (limited to 'Assets/Algorithms/Searching.cs')
-rw-r--r--Assets/Algorithms/Searching.cs35
1 files changed, 35 insertions, 0 deletions
diff --git a/Assets/Algorithms/Searching.cs b/Assets/Algorithms/Searching.cs
new file mode 100644
index 0000000..3489eac
--- /dev/null
+++ b/Assets/Algorithms/Searching.cs
@@ -0,0 +1,35 @@
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using AlgorithmCollection;
+
+namespace AlgorithmCollection.Searching
+{
+
+ public static class SearchingHelper
+ {
+
+ // 二分搜索,返回索引号
+ // O(logn)
+ public static int BinarySearch<T>(T[] dataList, T value) where T : IComparable, IEquatable<T>
+ {
+ int n = dataList.Length;
+ int left = 0;
+ int right = n - 1;
+ while(left <= right)
+ {
+ int middle = (right + left) / 2;
+ T midValue = dataList[middle];
+ if (value.Equals(midValue))
+ return middle;
+ if (value.CompareTo(midValue) > 0)
+ left = middle + 1;
+ if (value.CompareTo(midValue) < 0)
+ right = middle - 1;
+ }
+ return -1; // 没找到
+ }
+
+ }
+
+} \ No newline at end of file