This package provides efficient search and sorting methods, including Binary Search, Bubble Sort, and a Factorial Function.
npm install search-array-element
const { binarySearch, bubbleSort, factorial } = require('search-array-element');
Searches for an element in a sorted array using the binary search algorithm.
const arr = [1, 4, 5, 7, 8, 9];
const target = 7;
const index = binarySearch(arr, target);
console.log(index); // Output: 3
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.
const unsortedArr = [5, 3, 8, 1, 2];
const sortedArr = bubbleSort(unsortedArr);
console.log(sortedArr); // Output: [1, 2, 3, 5, 8]
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;
}
Finds the factorial of a number using recursion.
const num = 5;
console.log(factorial(num)); // Output: 120
function factorial(n) {
if (n === 0) return 1;
return n * factorial(n - 1);
}
Banti Singh
This project is licensed under the ISC License.