From 280c04a5d7df205c5271f15f1d61a9bbd66be548 Mon Sep 17 00:00:00 2001 From: orgin Date: Thu, 8 Sep 2022 09:18:18 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=E4=BA=8C=E5=88=86=E6=9F=A5?= =?UTF-8?q?=E6=89=BE=E7=AE=97=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- util/algorithms/BiSearch.go | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/util/algorithms/BiSearch.go b/util/algorithms/BiSearch.go index 4543ddb..5ed487b 100644 --- a/util/algorithms/BiSearch.go +++ b/util/algorithms/BiSearch.go @@ -10,7 +10,7 @@ type Element[ValueType NumberType] interface { } //BiSearch 二分查找,切片必需有序号。matchUp表示是否向上范围查找。比如:数列10 20 30 ,当value传入25时,返回结果是2,表示落到3的范围 -func BiSearch[ValueType NumberType, T Element[ValueType]](sElement []T, value ValueType, matchUp bool) int { +func BiSearch[ValueType NumberType, T Element[ValueType]](sElement []T, value ValueType, matchUp int) int { low, high := 0, len(sElement)-1 if high == -1 { return -1 @@ -28,12 +28,29 @@ func BiSearch[ValueType NumberType, T Element[ValueType]](sElement []T, value Va } } - if matchUp == true { + switch matchUp { + case 1: if (sElement[mid].GetValue()) < value && (mid+1 < len(sElement)-1) { return mid + 1 } return mid + case -1: + if (sElement[mid].GetValue()) > value { + if mid - 1 < 0 { + return -1 + } else { + return mid - 1 + } + } else if (sElement[mid].GetValue()) < value { + if (mid+1 < len(sElement)-1) { + return mid + 1 + } else { + return mid + } + } else { + return mid + } } return -1