From 04e9780b47d930e170e2ee555548caf2ac572340 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=A1=E5=9D=82=E6=98=B4?= Date: Sun, 22 Dec 2024 01:24:50 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=9E=E9=AA=8C=E5=85=AD=E5=AE=8C=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- homework6/test1.cpp | 2 +- homework6/test2.cpp | 40 ++++++++++++++++++++-------------------- 2 files changed, 21 insertions(+), 21 deletions(-) diff --git a/homework6/test1.cpp b/homework6/test1.cpp index fcc7807..7f8c550 100644 --- a/homework6/test1.cpp +++ b/homework6/test1.cpp @@ -13,7 +13,7 @@ int seqSearch(vector l,T value) { bool found = false; int index = 0; for (int i=0; i - -void ListBinaryCopy(vector p,vector sl,vector sr) { - int low=0; - int high=p.size()-1; - int mid=(low+high)/2; - - for (int i=low;i<=mid;i++) { - sl[i]=p[i]; +template +int BinarySearch(const vector& arr, T target, int left, int right) { + if (left > right) { + return -1; // 未找到目标值 } - for (int i=mid+1;i<=high;i++) { - sr[i]=p[i]; + int mid = left + (right - left) / 2; // 计算中间位置 + + cout << "正在查找第"< -int BinarySearch(vector l, T value) { - if (l.empty()) return -1; - - vector sub_list_left, sub_list_right; - ListBinaryCopy(l, sub_list_left); - - BinarySearch(sub_list_left, value); - BinarySearch(sub_list_right, value); +template +int BinarySearch(const vector& arr, T target) { + return BinarySearch(arr, target, 0, arr.size() - 1); } + int main() { vector l = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + const int index=BinarySearch(l, 9); + cout<