logo

Recherche linéaire en Java

La recherche linéaire est utilisée pour rechercher un élément clé parmi plusieurs éléments. La recherche linéaire est moins utilisée aujourd’hui car elle est plus lente que la recherche binaire et le hachage.

Algorithme:

  • Étape 1 : Parcourir le tableau
  • Étape 2 : Faites correspondre l'élément clé avec l'élément du tableau
  • Étape 3 : Si l'élément clé est trouvé, renvoie la position d'index de l'élément du tableau
  • Étape 4 : Si l'élément clé n'est pas trouvé, renvoyez -1

Voyons un exemple de recherche linéaire en Java où nous allons rechercher un élément séquentiellement à partir d'un tableau.

 public class LinearSearchExample{ public static int linearSearch(int[] arr, int key){ for(int i=0;i <arr.length;i++){ if(arr[i]="=" key){ return i; } -1; public static void main(string a[]){ int[] a1="{10,20,30,50,70,90};" int key="50;" system.out.println(key+' is found at index: '+linearsearch(a1, key)); < pre> <span> Test it Now </span> <p>Output:</p> <pre> 50 is found at index: 3 </pre> <h2>Linear Search in Java (Another way)</h2> <p>You can also use a method where array is not predefined. Here, user has to put the elements as input and select one element to check its location.</p> <pre> import java.util.Scanner; class LinearSearchExample2 { public static void main(String args[]) { int c, n, search, array[]; Scanner in = new Scanner(System.in); System.out.println(&apos;Enter number of elements&apos;); n = in.nextInt(); array = new int[n]; System.out.println(&apos;Enter those &apos; + n + &apos; elements&apos;); for (c = 0; c <n; c++) array[c]="in.nextInt();" system.out.println('enter value to find'); search="in.nextInt();" for (c="0;" c < n; { if (array[c]="=" search) * searching element is present system.out.println(search + ' at location 1) '.'); break; } n) isn't in array.'); pre> <p>Output:</p> <strong>Use image LinearSearchExample</strong> </n;></pre></arr.length;i++){>

Recherche linéaire en Java (une autre manière)

Vous pouvez également utiliser une méthode où le tableau n'est pas prédéfini. Ici, l'utilisateur doit mettre les éléments en entrée et sélectionner un élément pour vérifier son emplacement.

 import java.util.Scanner; class LinearSearchExample2 { public static void main(String args[]) { int c, n, search, array[]; Scanner in = new Scanner(System.in); System.out.println(&apos;Enter number of elements&apos;); n = in.nextInt(); array = new int[n]; System.out.println(&apos;Enter those &apos; + n + &apos; elements&apos;); for (c = 0; c <n; c++) array[c]="in.nextInt();" system.out.println(\'enter value to find\'); search="in.nextInt();" for (c="0;" c < n; { if (array[c]="=" search) * searching element is present system.out.println(search + \' at location 1) \'.\'); break; } n) isn\'t in array.\'); pre> <p>Output:</p> <strong>Use image LinearSearchExample</strong> </n;>