logo

Linearno iskanje v Javi

Linearno iskanje se uporablja za iskanje ključnega elementa med več elementi. Linearno iskanje se danes manj uporablja, ker je počasnejše od binarnega iskanja in zgoščevanja.

Algoritem:

  • 1. korak: prečkajte polje
  • 2. korak: Povežite ključni element z elementom matrike
  • 3. korak: Če je ključni element najden, vrnite položaj indeksa elementa matrike
  • 4. korak: Če ključni element ni najden, vrnite -1

Oglejmo si primer linearnega iskanja v Javi, kjer bomo zaporedno iskali element iz matrike.

 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++){>

Linearno iskanje v Javi (Drug način)

Uporabite lahko tudi metodo, kjer matrika ni vnaprej določena. Tukaj mora uporabnik vnesti elemente in izbrati en element, da preveri njegovo lokacijo.

 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;>