From 1a15c1b8c9de7a6f29de0923fe32070ce49c7dc9 Mon Sep 17 00:00:00 2001 From: ProStarGithub Date: Tue, 11 Oct 2022 23:35:06 +0530 Subject: [PATCH] Added JS Searching algorithms --- JAVASCRIPT/Algorithms/binarySearch.js | 27 +++++++++++++++++++++++++++ JAVASCRIPT/Algorithms/linearSearch.js | 9 +++++++++ 2 files changed, 36 insertions(+) create mode 100644 JAVASCRIPT/Algorithms/binarySearch.js create mode 100644 JAVASCRIPT/Algorithms/linearSearch.js diff --git a/JAVASCRIPT/Algorithms/binarySearch.js b/JAVASCRIPT/Algorithms/binarySearch.js new file mode 100644 index 0000000..750fdbe --- /dev/null +++ b/JAVASCRIPT/Algorithms/binarySearch.js @@ -0,0 +1,27 @@ +const binarySearch = (arr, searchElement) => { + // Method1) Soring Array + // arr.sort(function (a, b) { + // return a - b; + // }); + + // Method2) Sorting Array - Faster + const typedArray = Float32Array.from(arr); + const sortedArray = typedArray.sort(); + + let start = 0, + end = sortedArray.length - 1; + + while (start <= end) { + const middle = Math.floor((start + end) / 2); + + if (sortedArray[middle] === searchElement) return middle; + else if (sortedArray[middle] < searchElement) start = middle + 1; + else end = middle - 1; + } + + return -1; +}; + +// console.log(binarySearch([28, 59, 68, 16], 5)); // Output: -1 +// console.log(binarySearch([28, 59, 68, 16], 68)); // Output: 3 +// console.log(binarySearch([28, 59, 68, 16, 1, 6, 5], 68)); // Output: 6 diff --git a/JAVASCRIPT/Algorithms/linearSearch.js b/JAVASCRIPT/Algorithms/linearSearch.js new file mode 100644 index 0000000..c8f7de9 --- /dev/null +++ b/JAVASCRIPT/Algorithms/linearSearch.js @@ -0,0 +1,9 @@ +const linearSearch = (arr, searchElement) => { + for (let index = 0; index < arr.length; index++) { + if (arr[index] === searchElement) return index; + } + return -1; +}; + +// console.log(linearSearch([28, 59, 68, 16], 5)); // Output: -1 +// console.log(linearSearch([28, 59, 68, 16], 68)); // Output: 2