您的位置:首页 > 其它

查找算法之顺序搜索

2017-10-18 15:27 330 查看

顺序查找的思路:

设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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  顺序搜索
相关文章推荐