UNPKG

@lucadani7/algonodejs-for-beginners

Version:

Just a simple Node.js package with some basic algorithms perfect for people just starting out. It's got easy-to-understand TypeScript versions of stuff like sorting, searching, math with numbers, and messing with strings.

46 lines (45 loc) 1.53 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SearchingAlgorithms = void 0; class SearchingAlgorithms { static arrayIsSorted(arr) { for (let i = 0; i < arr.length - 1; ++i) { if (arr[i] > arr[i + 1]) { return false; } } return true; } static linearSearch(arr, valueToSearch) { for (let i = 0; i < arr.length; ++i) { if (arr[i] === valueToSearch) { console.log(`Element ${valueToSearch} is present at index ${i}.`); return; } } console.log(`Element ${valueToSearch} does not exist in array!`); } static binarySearch(arr, valueToSearch) { if (!this.arrayIsSorted(arr)) { console.log("The array is unsorted, so the value you want to search won't be searched binary!"); return; } let start = 0; let end = arr.length - 1; while (start <= end) { let middle = Math.floor((start + end) / 2); if (arr[middle] === valueToSearch) { console.log(`Element ${valueToSearch} found!`); return; } else if (arr[middle] < valueToSearch) { start = middle + 1; } else { end = middle - 1; } } console.log(`Element ${valueToSearch} does not exist in array!`); } } exports.SearchingAlgorithms = SearchingAlgorithms;