Що таке лінійний пошук?
Припустимо, вам надано список або масив елементів. Ви шукаєте певний предмет. Як ти це робиш?
Знайдіть число 13 у поданому списку.

Ви просто подивіться на список і ось він!

Тепер, як сказати комп’ютеру знайти його?
Комп’ютер не може розглядати більше значення, ніж значення в даний момент часу. Отже, він бере один елемент із масиву і перевіряє, чи він такий самий, як той, що ви шукаєте.

Перший елемент не збігався. Тож переходьте до наступного.

І так далі…
Це робиться до тих пір, поки не буде знайдено збіг або поки всі елементи не будуть перевірені.

У цьому алгоритмі ви можете зупинитися, коли предмет знайдено, і тоді немає необхідності шукати далі.
То скільки часу знадобиться для виконання операції лінійного пошуку? У найкращому випадку вам може пощастити, і предмет, який ви розглядаєте, може бути на першій позиції в масиві!
Але в гіршому випадку вам доведеться переглянути кожен предмет, перш ніж знайти його в останньому місці або до того, як ви зрозумієте, що елемента немає в масиві.
Тому складність лінійного пошуку дорівнює O (n).
Якби елемент, який потрібно шукати, жив на першому блоці пам'яті, то складність була б такою: O (1).
Код функції лінійного пошуку в JavaScript показаний нижче. Ця функція повертає позицію елемента, який ми шукаємо в масиві. Якщо елемента немає в масиві, функція поверне нуль.
Приклад у Javascript
function linearSearch(arr, item) { // Go through all the elements of arr to look for item. for (var i = 0; i < arr.length; i++) { if (arr[i] === item) { // Found it! return i; } } // Item not found in the array. return null; }
Приклад у Ruby
def linear_search(target, array) counter = 0 while counter < array.length if array[counter] == target return counter else counter += 1 end end return nil end
Приклад у C ++
int linear_search(int arr[],int n,int num) { for(int i=0;i
Example in Python
def linear_search(array, num): for i in range(len(array)): if (array[i]==num): return i return -1
Global Linear Search
What if you are searching the multiple occurrences of an element? For example you want to see how many 5’s are in an array.
Target = 5
Array = [ 1, 2, 3, 4, 5, 6, 5, 7, 8, 9, 5]
This array has 3 occurrences of 5s and we want to return the indexes (where they are in the array) of all of them.
This is called global linear search and you will need to adjust your code to return an array of the index points at which it finds your target element.
When you find an index element that matches your target, the index point (counter) will be added in the results array. If it doesn’t match, the code will continue to move on to the next element in the array by adding 1 to the counter.
def global_linear_search(target, array) counter = 0 results = [] while counter < array.length if array[counter] == target results << counter counter += 1 else counter += 1 end end if results.empty? return nil else return results end end
Why linear search is not efficient
There is no doubt that linear search is simple. But because it compares each element one by one, it is time consuming and therefore not very efficient. If we have to find a number from, say, 1,000,000 numbers and that number is at the last position, a linear search technique would become quite tedious.
So you should also learn about bubble sort, quick sort and other more efficient algorithms.
Other search algorithms:
How to implement quick sort
Binary search algorithm
Jump search algorithm
Search algorithms explained with examples
Implement a binary search algorithm in Java without recursion
More info on search algorithms

Original text