logo

Lineær søgning i Java

Lineær søgning bruges til at søge et nøgleelement fra flere elementer. Lineær søgning bruges mindre i dag, fordi den er langsommere end binær søgning og hashing.

Algoritme:

  • Trin 1: Gå gennem arrayet
  • Trin 2: Match nøgleelementet med array-elementet
  • Trin 3: Hvis nøgleelementet er fundet, returner indekspositionen for array-elementet
  • Trin 4: Hvis nøgleelementet ikke findes, returneres -1

Lad os se et eksempel på lineær søgning i java, hvor vi skal søge et element sekventielt fra et array.

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

Lineær søgning i Java (en anden måde)

Du kan også bruge en metode, hvor array ikke er foruddefineret. Her skal brugeren sætte elementerne som input og vælge et element for at kontrollere dets placering.

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