Java教程

Java中的线性搜索

线性搜索用于从多个元素中搜索关键元素。如今,线性搜索已不再使用,因为它比二进制搜索和散列要慢。
算法:
第1步: 遍历数组 第2步: 将关键元素与数组元素匹配 第3步: 如果找到关键元素,则返回数组元素的索引位置 第4步: 如果找不到关键元素,则返回-1
让我们看一下Java中线性搜索的示例,在该示例中,我们将从数组中顺序搜索元素。
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;
            }
        }
        return -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));
    }
}
输出:
50 is found at index: 3

Java中的线性搜索(另一种方式)

您还可以使用未预定义数组的方法。在这里,用户必须将元素作为输入并选择一个元素以检查其位置。
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; c++) {
            if (array[c] == search)
            /*
            Searching element is present
            */
            {
                System.out.println(search + " is present at location " + (c + 1) + ".");
                break;
            }
        }
        if (c == n)
        /*
        Element to search isnt present
        */
        System.out.println(search + " isn't present in array.");
    }
}
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4