Search element in an array

In this program, we search for a specific element in an array using JavaScript.

Example

Input
------
array: [1,2,3,4,7,10,2]
search: 7

Output
------
Element found at position 5

Program

//Find an element in array

function searchElementInArray(arr, search) {
    let found = 0;
    let position = 0;

    for(let i = 0; i < arr.length; i++) {
        if(arr[i] === search) { //check weather element exist in array or not
            found = 1;
            position = i + 1;
            break;
        }
    }

    if(found === 1) {
        console.log('Element found at position ' + position);
    }else{
        console.log('Element does not exist');
    }
}

searchElementInArray([1,2,3,4,7,10,2],7); // Big O of this program is : O(n)

Leave a Reply

Your email address will not be published.