Developing a linear search algorithm

To refresh our memory about linear algorithms, let's pick a random array that contains {43, 21, 26, 38, 17, 30, 25, 18}. We then have to find the index where 30 is stored. As we can see in the array, 30 is in index 5 (since the array is zero-based indexing); however, if we find an unexisting item, the algorithm should return -1. The following is the method of linear search named LinearSearch():

int LinearSearch(    int arr[],    int startIndex,    int endIndex,    int val){    // Iterate through the start index    // to the end index and    // return the searched value's index    for(int i = startIndex; i < endIndex; ++i)    {        if(arr[i] == val)        {            return i;        }    }    // return -1 if no val is found    return -1;}

As we can see in the LinearSearch() ...

Get C++ Data Structures and Algorithms now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.