Линеарна претрага

У овом упутству ћете научити о линеарном претраживању. Такође ћете наћи радне примере линеарног претраживања Ц, Ц ++, Јава и Питхон.

Линеарно претраживање је најједноставнији алгоритам претраживања који тражи елемент на листи у низу. Почињемо на једном крају и проверавамо сваки елемент док се не пронађе жељени елемент.

Како функционише линеарна претрага?

Следе следећи кораци за тражење елемента k = 1на доњој листи.

Низ који треба тражити
  1. Почните од првог елемента, упоредите к са сваким елементом к. Упоредите са сваким елементом
  2. Ако x == k, вратите индекс. Елемент је пронађен
  3. Иначе, повратак није пронађен.

Линеарни алгоритам претраживања

ЛинеарСеарцх (низ, кључ) за сваку ставку у низу ако итем == валуе враћа свој индекс

Примери за Питхон, Јава и Ц / Ц ++

Питхон Јава Ц Ц ++
 # Linear Search in Python def linearSearch(array, n, x): # Going through array sequencially for i in range(0, n): if (array(i) == x): return i return -1 array = (2, 4, 0, 1, 9) x = 1 n = len(array) result = linearSearch(array, n, x) if(result == -1): print("Element not found") else: print("Element found at index: ", result)
 // Linear Search in Java class LinearSearch ( public static int linearSearch(int array(), int x) ( int n = array.length; // Going through array sequencially for (int i = 0; i < n; i++) ( if (array(i) == x) return i; ) return -1; ) public static void main(String args()) ( int array() = ( 2, 4, 0, 1, 9 ); int x = 1; int result = linearSearch(array, x); if (result == -1) System.out.print("Element not found"); else System.out.print("Element found at index: " + result); ) )
 // Linear Search in C #include int search(int array(), int n, int x) ( // Going through array sequencially for (int i = 0; i < n; i++) if (array(i) == x) return i; return -1; ) int main() ( int array() = (2, 4, 0, 1, 9); int x = 1; int n = sizeof(array) / sizeof(array(0)); int result = search(array, n, x); (result == -1) ? printf("Element not found") : printf("Element found at index: %d", result); )
 // Linear Search in C++ #include using namespace std; int search(int array(), int n, int x) ( // Going through array sequencially for (int i = 0; i < n; i++) if (array(i) == x) return i; return -1; ) int main() ( int array() = (2, 4, 0, 1, 9); int x = 1; int n = sizeof(array) / sizeof(array(0)); int result = search(array, n, x); (result == -1) ? cout << "Element not found" : cout << "Element found at index: " << result; )

Комплексности линеарног претраживања

Сложеност времена: О (н)

Сложеност простора: O(1)

Апликације за линеарно претраживање

  1. За операције претраживања у мањим низовима (<100 предмета).

Занимљиви Чланци...