Dans ce didacticiel, vous découvrirez la recherche linéaire. Vous trouverez également des exemples fonctionnels de recherche linéaire C, C ++, Java et Python.
La recherche linéaire est l'algorithme de recherche le plus simple qui recherche un élément dans une liste dans un ordre séquentiel. Nous commençons à une extrémité et vérifions chaque élément jusqu'à ce que l'élément souhaité ne soit pas trouvé.
Comment fonctionne la recherche linéaire?
Les étapes suivantes sont suivies pour rechercher un élément k = 1
dans la liste ci-dessous.

- Commencez par le premier élément, comparez k avec chaque élément x.
Comparer avec chaque élément
- Si
x == k
, retournez l'index.Élément trouvé
- Sinon, retour non trouvé.
Algorithme de recherche linéaire
LinearSearch (tableau, clé) pour chaque élément du tableau si item == value renvoie son index
Exemples Python, Java et C / C ++
Python Java C C ++ # 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; )
Complexités de la recherche linéaire
Complexité temporelle: O (n)
Complexité de l'espace: O(1)
Applications de recherche linéaire
- Pour les opérations de recherche dans des tableaux plus petits (<100 éléments).