search-array-element

1.0.0 • Public • Published

Search Array Element - NPM Package

Description

This package provides efficient search and sorting methods, including Binary Search, Bubble Sort, and a Factorial Function.

Installation

npm install search-array-element

Usage

Import the module

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.

const arr = [1, 4, 5, 7, 8, 9];
const target = 7;
const index = binarySearch(arr, target);
console.log(index); // Output: 3

Implementation

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.

const unsortedArr = [5, 3, 8, 1, 2];
const sortedArr = bubbleSort(unsortedArr);
console.log(sortedArr); // Output: [1, 2, 3, 5, 8]

Implementation

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.

const num = 5;
console.log(factorial(num)); // Output: 120

Implementation

function factorial(n) {
    if (n === 0) return 1;
    return n * factorial(n - 1);
}

Repository & Issues

Author

Banti Singh

License

This project is licensed under the ISC License.

Package Sidebar

Install

npm i search-array-element

Weekly Downloads

2

Version

1.0.0

License

ISC

Unpacked Size

3.99 kB

Total Files

3

Last publish

Collaborators

  • bantisingh97