您的位置:首页 > 理论基础 > 数据结构算法

数据结构与算法----顺序查找法

2017-09-18 20:22 471 查看
两种方法

1.普通方法,倒序(顺序)遍历数组中的每个元素,与查找元素相比较,时间复杂度为O(n)。

static int search_seq2(int a[],int n,int key) {
for(int i = n-1;i>=0;i--) {
if(a[i] == key)
return i;
}
return -1 ;
}


2.哨兵方法。将数组第一个元素置为要查找的元素,然后倒序遍历数组每一个元素,和查找元素相比。但是因为数组第一个为查找元素,所以当找不到元素的时候,就会把数组第一个元素和查找元素相比。:没有判断越界的代码了,即普通方法中的“i>=0”。对于数据较多(>=1000)的情况下,哨兵比普通方法所需平均时间减少了一半。

static int search_seq1(int a[],int n ,int key) {
a[0] = key;
int i = n;
while(a[i] != key) {//没有越界判断
i--;
}
return i;
}


整个测试源代码:

public class Search_seq {
//哨兵
static int search_seq1(int a[],int n ,int key) {
a[0] = key;
int i = n;
while(a[i] != key) {
i--;
}
return i;
}
//无哨兵
static int search_seq2(int a[],int n,int key) { for(int i = n-1;i>=0;i--) { if(a[i] == key) return i; } return -1 ; }

public static void main(String[] args) {

int[] b = {0,2,4,4,5,9,23};
int i = Search_seq.search_seq1(b, b.length-1, 4);
if(i!=-1) {
System.out.println("find!");
}
else
System.out.println("notexit!");

int[] a = {2,4,4,5,9,23};
int i = Search_seq.search_seq2(a,a.length,4);
if(i != 0 )
System.out.println("find!");
else
System.out.println("notexit!");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构 算法 查找