From 5d81d8d8b4062def695c27fa02f67625871e8dce Mon Sep 17 00:00:00 2001 From: chai Date: Mon, 21 Jun 2021 22:59:39 +0800 Subject: *misc --- Assets/Algorithms/Searching.cs | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Assets/Algorithms/Searching.cs (limited to 'Assets/Algorithms/Searching.cs') 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[] dataList, T value) where T : IComparable, IEquatable + { + 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 -- cgit v1.1-26-g67d0