Linearno pretraživanje koristi se za pretraživanje ključnog elementa iz više elemenata. Linearno pretraživanje danas se manje koristi jer je sporije od binarnog pretraživanja i hashiranja.
Algoritam:
- Korak 1: Pređite nizom
- Korak 2: Povežite ključni element s elementom niza
- Korak 3: Ako je ključni element pronađen, vratite poziciju indeksa elementa niza
- Korak 4: Ako ključni element nije pronađen, vratite -1
Pogledajmo primjer linearne pretrage u Javi gdje ćemo pretraživati element sekvencijalno iz niza.
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('Enter number of elements'); n = in.nextInt(); array = new int[n]; System.out.println('Enter those ' + n + ' elements'); 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++){>
Linearno pretraživanje u Javi (drugi način)
Također možete koristiti metodu u kojoj niz nije unaprijed definiran. Ovdje korisnik mora staviti elemente kao unos i odabrati jedan element da provjeri njegovu lokaciju.
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('Enter number of elements'); n = in.nextInt(); array = new int[n]; System.out.println('Enter those ' + n + ' elements'); 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;>