From 62389eefc5beccbb16c2c7cc1a125da5441e80dc Mon Sep 17 00:00:00 2001 From: "green.carlos" Date: Mon, 30 Mar 2026 11:57:05 -0700 Subject: [PATCH] 10.4 Sorted Search No Size simplified solution --- .../sortedSearchNoSizeV2.js | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 chapter10/10.04 - Sorted Search No Size/sortedSearchNoSizeV2.js diff --git a/chapter10/10.04 - Sorted Search No Size/sortedSearchNoSizeV2.js b/chapter10/10.04 - Sorted Search No Size/sortedSearchNoSizeV2.js new file mode 100644 index 0000000..1ecd8c9 --- /dev/null +++ b/chapter10/10.04 - Sorted Search No Size/sortedSearchNoSizeV2.js @@ -0,0 +1,39 @@ +function Listy(list) { + this.list = list.length === 0 ? [] : list; +} + +Listy.prototype.elementAt = function (index) { + return this.list[index]; // assuming we can only check if the element exists, not the length +}; + +const sortedSearch = function (list, val) { + let left = 0; + let right = Number.MAX_SAFE_INTEGER; // Maximum number that's valid in the language + + if (list.elementAt(left) === val) return left; // quick check to see if we already hit the number + if (list.elementAt(right) === val) return right; + + while (left < right) { + const mid = Math.floor(Math.abs((left + right) / 2)); + + if (list.elementAt(mid) === val) { + return mid; + } else if (list.elementAt(mid) > val || list.elementAt(mid) === undefined) { + right = mid; + } else if (list.elementAt(mid) < val) { + left = mid + 1; + } + } + + return -1; +}; + +const listy = new Listy([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]); + +console.log(sortedSearch(listy, 0), 0); +console.log(sortedSearch(listy, 2), 2); +console.log(sortedSearch(listy, 6), 6); + +console.log(sortedSearch(listy, 15), 15); +console.log(sortedSearch(listy, 16), -1); +console.log(sortedSearch(listy, 7), 7);