Comp 110 Searching Arrays

Searching Arrays

STEP 1: Set up a loop that allows you to iterate through your array..this can be done with either a for or a while loop, however for this example we will be using a for loop. 

Note: is this searching algorithm taking place in a function? Write the skeleton of your function definition as described here.

//the below indexOf function will return the index position of the number n in the array arr
//if the number does not exist in the array, return -1
let indexOf = (arr: number[], n: number): number => {
    for (let i = 0; i < arr.length; i++) {
      //to be written
    }
};

STEP 2: Inside your loop, set up a condition that checks the value of each element in the array based on the index from your for loop.

If we find the element we are looking for, what do we want to happen? In this case, we immediately want to return the index (represented by i). If we have not yet found the element, we want the loop to continue iterating.

let indexOf = (arr: number[], n: number): number => {
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] === n) {
            return i;
        }
// if the element has not yet been found, continue iterating
// we do not need an 'else'
    }

};

STEP 3: Accommodate any edge cases that may be missing. What happens when the element is not found?

In this example, we want to return -1 if n is not found. At what line do we know that the element does not exist in the array? After the for loop finishes iterating (since we will have looked at all the elements in the array). So after the for loop ends, insert your edge case.

let indexOf = (arr: number[], n: number): number => {
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] === n) {
            return i;
        }
    }
    return -1;
};