From 3b95d366dce5015ddaa4951b4900f8d36c61e1b5 Mon Sep 17 00:00:00 2001 From: YuJian Date: Fri, 20 May 2022 17:34:35 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BA=8C=E5=88=86=E6=9F=A5=E6=89=BE=20indexOf?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- BinarySearch/IndexOf_BinarySearch.test.ts | 0 BinarySearch/IndexOf_BinarySearch.ts | 34 +++++++++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 BinarySearch/IndexOf_BinarySearch.test.ts create mode 100644 BinarySearch/IndexOf_BinarySearch.ts diff --git a/BinarySearch/IndexOf_BinarySearch.test.ts b/BinarySearch/IndexOf_BinarySearch.test.ts new file mode 100644 index 0000000..e69de29 diff --git a/BinarySearch/IndexOf_BinarySearch.ts b/BinarySearch/IndexOf_BinarySearch.ts new file mode 100644 index 0000000..4336388 --- /dev/null +++ b/BinarySearch/IndexOf_BinarySearch.ts @@ -0,0 +1,34 @@ +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; +}; + +// const arr = []; +// for (let index = 0; index < 100000000; index++) { +// arr.push(index); +// } + +// console.time("indexOf_BinarySearch"); +// indexOf_BinarySearch(arr, 99999999) +// console.timeEnd("indexOf_BinarySearch"); + +// console.time("indexOf"); +// arr.indexOf(99999999) +// console.timeEnd("indexOf");