The basics of programming in c++ for beginners

Linear search in C++

100% programmers, during training, sooner or later face the need to check for certain values in an array. There are several well-known search algorithms in programming languages. Now we look at the simplest of them (but not the most effective) – linear search or sequential search. Due to the fact, that search is conducted through the full brute force elements in the array and compare its value with the specified key, the algorithm is quite low speed.

To tell there is nothing special – It is better to show a linear search to work. In the example below to declare an array 50 elements and fill it using random number generator rand(). Prompt the user to enter the desired value with the keyboard and implement check for this value in our array. If a value is found in any element of the array – We display the index of the element. This is a classic example . It is hard and come up with something better to demonstrate the linear search in C ++.

Function performs a linear search is defined in strings 62-70. She returns to the program -1 in that case, if the value, is looking for a user, will not be found in the array. If the value is found – function returns the array index, wherein the value is stored.

Run:

линейный поиск с++, linear search c ++, for beginners, Search algorithms ++, for Dummies, incremental search, ʙrutfors

In the absence of values ​​in an array:

линейный поиск с++, linear search c ++, for beginners, Search algorithms ++, for Dummies, incremental search, ʙrutfors

After looking at the first picture, you will immediately notice, that in a cell with index 6 the desired value is found and the program shuts down, although the cells 23 and 33 it array are the same values. If you're okay with that, the index of the first element and is the result of the work program. Otherwise, the program should be finished, to find and record (for example, in a single array) all indices of cells, store the desired number (key).

Typically, a linear search is used to search in a small single array, that is not sorted. In other cases,, better and more efficient first sort the array and to use other search algorithms. For example binary (binary) Search or other.

3 thoughts on “Linear search in C++

  1. Function, checking the presence of the element in the array should return bool (true if the element is false, and if it is not).
    There is no sense to return the value of the element, tk. client (Togo, who caused function) already have this value – because he gave it as the second argument, Why should he get it back?
    To return -1 in the absence of the element even more pointless, Imagine that I want to check for values -1 array.

Leave a Reply to Programmer_blog Cancel reply

Your email address will not be published. Required fields are marked *