Skip to Content
C++ Data Structures and Algorithms
book

C++ Data Structures and Algorithms

by Wisnu Anggoro
April 2018
Intermediate to advanced content levelIntermediate to advanced
322 pages
6h 57m
English
Packt Publishing
Content preview from C++ Data Structures and Algorithms

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() ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Data Structures and Algorithms Using C++

Data Structures and Algorithms Using C++

Ananda Rao Akepogu, Radhika Raju Palagiri
C++ Data Structures and Algorithm Design Principles

C++ Data Structures and Algorithm Design Principles

John Carey, Anil Achary, Shreyans Doshi, Payas Rajan
C++ Plus Data Structures, 6th Edition

C++ Plus Data Structures, 6th Edition

Nell Dale, Chip Weems, Tim Richards

Publisher Resources

ISBN: 9781788835213Supplemental Content