資料結構之尋找,資料結構尋找

來源:互聯網
上載者:User

資料結構之尋找,資料結構尋找

 前言:尋找是開發中用的非常多的一項,比如mysql中的尋找,下面主要簡單介紹一下尋找。

1:線性表尋找

線性表尋找主要分為順序尋找和鏈式尋找,順序表尋找都是從一端到另一端進行遍曆。比如下面代碼

public int indexOf(T x){        if (x!=null){            for (int i=0;i<this.len;i++){                if (this.element[i].equals(x)){                    return i;                }            }        }        return -1;    }    public T search(T key) {        return indexOf(key)==-1?null:(T) this.element[indexOf(key)];    }

第二種是鏈式尋找也非常簡單

public T search(T key) {        if (key==null){            return null;        }        Node<T> p=this.head.next;        while (p!=null){            if (p.data.equals(key)){                return p.data;            }            p=p.next;        }        return null;    }
2:基於有序順序表的二分尋找

這個用的比較多,因為查詢效率比較高,但是有限制條件,1是順序儲存,2必須有序,所以每次只需要和中間值進行比對,如果大於中間值,說明在key值在後面,如果小於中間值,說明key在前面。

 public static<T> int binarySearch(Comparable<T>[] values,int begin,int end,T key) {        if (key != null) {            while (begin <= end) {                int mid = (begin + end) / 2;                if (values[mid].compareTo(key) == 0) {                    return mid;                }                if (values[mid].compareTo(key) < 0) {                    begin = mid + 1;                }                if (values[mid].compareTo(key) > 0) {                    end = mid - 1;                }            }        }        return -1;    }    public static int binarySearch(int[] arrays, int key) {        if (arrays == null || arrays.length == 0) {            return -1;        }        int start=0,end=arrays.length-1;        while (start <=end) {            int mid = (start + end) / 2;            if (arrays[mid] == key) {                return mid;            }            if (arrays[mid] < key) {                start = mid + 1;            }            if (arrays[mid] > key) {                end = mid - 1;            }        }        return -1;    }
3:分塊索引尋找

我們都知道查字典,首先要查詢是字的拼音,然後定位到字頁數的一個位置,比如尋找張這個字,我們先查詢z,然後看哪些頁是z,然後在這一塊進行尋找。ok我們做個簡單的例子

現在我們已知一個數組裡面存放的是Java的關鍵字,那麼我們給出一個關鍵字來判斷是否在這個數組中。首先我們看下關鍵字的數組

  private static String[] keyWords={"abstract","assert","boolean","break","byte","case",           "catch","char","continue","default","do","double","else","extend","false","final",   "finally","float","for","if","implements","import","instaceof","in","interface",   "long","native","new","null","package","private","protectd","public","return","short",   "static","super","switch","synchronized","this","throw","transient","true","try","void","volatile","while"};

然後我們思考一下建立索引,因為英文單詞是26個字母組成,那麼我們效仿字典,把26個字母存起來,然後記錄每個字母的位置。

 private static class IndexItem implements Comparable<IndexItem>{        String frist;        int start;        public IndexItem(String frist,int start){            this.frist=frist;            this.start=start;        }

其中frist是字母,二start是字母的索引,比如abstract是a0,那麼assert就是a1了以此類推

  public int compareTo(IndexItem o) {            return this.frist.compareTo(o.frist);        }
  private static IndexItem[] index;索引表        static {            index = new IndexItem[26];            int i = 0, j = 0, size = 0;            for (i = 0; j < keyWords.length && i < index.length; i++) {                char ch = keyWords[j].charAt(0);                IndexItem item = new IndexItem(ch + "", j);                if (item != null) {                    index[i] = item;                    size++;                }                j++;                while (j < keyWords.length && keyWords[j].charAt(0) == ch) {                    j++;                }            }            int oldCount = index.length;利用trimTosize方法對數組進行壓縮            if (size < oldCount) {                IndexItem[] items = index;                index = new IndexItem[size];                for (int m = 0; m < size; m++) {                    index[m]  = items[m];                }            }        }

我們建立一個靜態塊,在類被載入的時候運行。最後我們利用2次2分尋找第一找到索引,然後通過索引匹配到值

    public static boolean isKeyWord(String str){            IndexItem indexItem=new IndexItem(str.substring(0,1),-1);            int pos=BSArry.binarySearch(index,indexItem);            int begin=index[pos].start;            int end;            if (pos==index.length-1){                end=keyWords.length-1;            }else {                 end=index[pos+1].start-1;            }            return BSArry.binarySearch(keyWords,begin,end,str)>=0;        }
4:散列表的尋找

散列的尋找非常高效,但是我們必須要完成2項工作,一個是散列函數,另一個是解決衝突。下面看一下如何利用單鏈表簡單的實現hash。

public class HashSet<T> {    private SingleLinkedList<T>[] table;    public HashSet(int size) {        this.table = new SingleLinkedList[Math.abs(size)];        for (int i = 0; i < table.length; i++) {            table[i] = new SingleLinkedList<T>();//製造單鏈表        }    }    public HashSet() {        this(97);    }    private int hash(T x) {//利用hashCode解決        int key = Math.abs(x.hashCode());        return key % table.length;    }    public void insert(T x) {        this.table[hash(x)].insert(0, x);    }    public void remove(T x) {        this.table[hash(x)].remove(x);    }    public T search(T key) {        return table[hash(key)].search(key);    }}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.