April 2018
Intermediate to advanced
322 pages
6h 57m
English
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() ...