From a32ff59676cad5ad791e6711023e5ff51fa873ab Mon Sep 17 00:00:00 2001 From: orgin Date: Fri, 11 Nov 2022 14:17:29 +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=EF=BC=8C=E8=A1=A5=E5=85=85=E6=B3=A8?= =?UTF-8?q?=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- util/algorithms/BiSearch.go | 29 +++++++++++++++++++---------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/util/algorithms/BiSearch.go b/util/algorithms/BiSearch.go index 5ed487b..c10fada 100644 --- a/util/algorithms/BiSearch.go +++ b/util/algorithms/BiSearch.go @@ -1,6 +1,5 @@ package algorithms - type NumberType interface { int | int8 | int16 | int32 | int64 | string | float32 | float64 | uint | uint8 | uint16 | uint32 | uint64 } @@ -9,7 +8,15 @@ type Element[ValueType NumberType] interface { GetValue() ValueType } -//BiSearch 二分查找,切片必需有序号。matchUp表示是否向上范围查找。比如:数列10 20 30 ,当value传入25时,返回结果是2,表示落到3的范围 +/* +BiSearch 二分查找,切片必需有序 +matchUp规则如下: +参数为0时,则一定要找到相等的值 +参数-1时,找value左边的值,例如:[10,20,30,40],当value为9时返回-1; 当value为11时,返回0 当value为41时,返回 3 +参数 1时,找value右边的值,例如:[10,20,30,40],当value为9时返回 0; 当value为11时,返回1 当value为41时,返回-1 + +返回-1时代表没有找到下标 +*/ func BiSearch[ValueType NumberType, T Element[ValueType]](sElement []T, value ValueType, matchUp int) int { low, high := 0, len(sElement)-1 if high == -1 { @@ -30,24 +37,26 @@ func BiSearch[ValueType NumberType, T Element[ValueType]](sElement []T, value Va switch matchUp { case 1: - if (sElement[mid].GetValue()) < value && - (mid+1 < len(sElement)-1) { + if (sElement[mid].GetValue()) < value { + if mid+1 >= len(sElement) { + return -1 + } return mid + 1 } return mid case -1: if (sElement[mid].GetValue()) > value { - if mid - 1 < 0 { + 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 - } + //if mid+1 < len(sElement)-1 { + // return mid + 1 + //} else { + return mid + //} } else { return mid }