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

来源:互联网 发布:interbase数据库启动 编辑:程序博客网 时间:2024/06/08 19:00

两种方法
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!");        }    }
原创粉丝点击