UNPKG

search-array-element

Version:
118 lines (82 loc) 2.31 kB
# Search Array Element - NPM Package ## Description This package provides efficient search and sorting methods, including **Binary Search**, **Bubble Sort**, and a **Factorial Function**. ## Installation ```sh npm install search-array-element ``` ## Usage ### Import the module ```js const { binarySearch, bubbleSort, factorial } = require('search-array-element'); ``` ### Methods & Examples #### 1. Binary Search **Searches for an element in a sorted array using the binary search algorithm.** ```js const arr = [1, 4, 5, 7, 8, 9]; const target = 7; const index = binarySearch(arr, target); console.log(index); // Output: 3 ``` #### Implementation ```js function binarySearch(arr, target) { let left = 0; let right = arr.length - 1; while (left <= right) { let mid = Math.floor((left + right) / 2); if (arr[mid] === target) { return mid; // Target found } else if (arr[mid] < target) { left = mid + 1; } else { right = mid - 1; } } return -1; // Target not found } ``` --- #### 2. Bubble Sort **Sorts an array using the Bubble Sort algorithm.** ```js const unsortedArr = [5, 3, 8, 1, 2]; const sortedArr = bubbleSort(unsortedArr); console.log(sortedArr); // Output: [1, 2, 3, 5, 8] ``` #### Implementation ```js function bubbleSort(arr) { let n = arr.length; for (let i = 0; i < n - 1; i++) { for (let j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]; } } } return arr; } ``` --- #### 3. Factorial **Finds the factorial of a number using recursion.** ```js const num = 5; console.log(factorial(num)); // Output: 120 ``` #### Implementation ```js function factorial(n) { if (n === 0) return 1; return n * factorial(n - 1); } ``` ## Repository & Issues - [GitHub Repository](https://github.com/BunniSingh/Creating-own-npm-package_day3-classwork) - [Report Issues](https://github.com/BunniSingh/Creating-own-npm-package_day3-classwork/issues) ## Author **Banti Singh** ## License This project is licensed under the ISC License.