From 07a059c2f53a055fe41f5a36fa0159200cb77183 Mon Sep 17 00:00:00 2001 From: YuJian Date: Fri, 20 May 2022 17:33:57 +0800 Subject: [PATCH] vault backup: 2022-05-20 17:33:57 --- .../算法之美 - 二分.md | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/数据结构与算法之美/算法之美 - 二分.md b/数据结构与算法之美/算法之美 - 二分.md index ee596c6..8148ec1 100644 --- a/数据结构与算法之美/算法之美 - 二分.md +++ b/数据结构与算法之美/算法之美 - 二分.md @@ -1,3 +1,25 @@ ## 实现一个基于二分查找的整形数组查找 +```javascript +const indexOf_BinarySearch = (dataArr: number[], num: number): number => { + let n1 = 0; + let n2 = dataArr.length - 1; + if (n1 === num) return n1; + if (n2 === num) return n2; + + while (n1 <= n2) { + const mid = Math.floor((n1 + n2) / 2); + if (num > dataArr[mid]) { + n1 = mid + 1; + } else if (num < dataArr[mid]) { + n2 = mid - 1; + } else { + return mid; + } + } + + return -1; +}; +``` + ## 两数之和 \ No newline at end of file