search-array-element
Version:
Search ele efficiently with binary search
118 lines (82 loc) • 2.31 kB
Markdown
This package provides efficient search and sorting methods, including **Binary Search**, **Bubble Sort**, and a **Factorial Function**.
```sh
npm install search-array-element
```
```js
const { binarySearch, bubbleSort, factorial } = require('search-array-element');
```
**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
```
```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
}
```
---
**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]
```
```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 + 1]] = [arr[j + 1], arr[j]];
}
}
}
return arr;
}
```
---
**Finds the factorial of a number using recursion.**
```js
const num = 5;
console.log(factorial(num)); // Output: 120
```
```js
function factorial(n) {
if (n === 0) return 1;
return n * factorial(n - 1);
}
```
- [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)
**Banti Singh**
This project is licensed under the ISC License.