查找算法之顺序搜索

来源:互联网 发布:文件集中管理 编程 编辑:程序博客网 时间:2024/05/21 20:30

顺序查找的思路:

设A[1..n]为一个n个元素的数组,判定给定元素x是否在A中,顺序查找的思路如下:扫描A中的所有元素,将每个元素与x比较,如果在j次比较后(1<=j<=n)搜索成功,即x=A[j],则返回j的值,否则返回-1,表示没有找到。

顺序查找的实现:

/** * 顺序搜索 * Created by yuzhan on 2017/10/18. */public class main {    public static int LinearSearch(int[] A, int x){        int j = 0;        int n = A.length;        while(j < n && x != A[j]){            j++;        }        if(j < n)            return j;        else            return -1;    }    public static void main(String[] args) {        int[] A = {2,1,3,6,4,23,65,75,34,67,32};        int x = 32;        int index = main.LinearSearch(A,x);        System.out.print(index);    }}
原创粉丝点击