Search for Data Structures

Source: Internet
Author: User
Tags comparable

Search for Data Structures

Searching is a very many item used in development, such as searching in mysql. The following is a brief introduction to searching.

1: Linear table search

Linear table searches are divided into sequential searches and chained searches. Sequential table searches are traversed from one end to the other. For example, the following code

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)];    }

The second is chain search, which is also very simple.

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: Binary Search Based on ordered sequence table

This is usually used because the query efficiency is relatively high, but there are restrictions: 1 is sequential storage, 2 must be ordered, so each time you only need to compare with the median value, if it is greater than the median value, it indicates that the key value is followed by the key value. If the value is smaller than the intermediate value, it indicates that the key is located at the beginning.

 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: block index search

We all know that to look up the dictionary, we need to first query the Pinyin of the word, and then locate a location of the number of pages of the word. For example, to find the word, we need to first query z and then see which pages are z, then search for it in this area. OK. Let's make a simple example.

Now we know that a Java keyword is stored in an array, so we will give a keyword to determine whether it is in this array. First, let's look at the array of keywords.

  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"};

Then let's think about how to create an index. Because the English word is made up of 26 letters, we use a dictionary to store 26 letters and record the location of each letter.

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

Here, frist is a letter, and binary start is a letter index. For example, if abstract is a0, assert is a1, and so on.

  public int compareTo(IndexItem o) {            return this.frist.compareTo(o.frist);        }
Private static IndexItem [] index; index table 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; Use the trimTosize method to compress the array if (size <oldCount) {IndexItem [] items = index; index = new IndexItem [size]; for (int m = 0; m <size; m ++) {index [m] = items [m] ;}}

We create a static block and run it when the class is loaded. Finally, we use two queries to find the first index and then match the value through the index.

    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: search for a hash

Hash search is very efficient, but we must complete two tasks: Hash function and conflict resolution. The following describes how to use a single-chain table to implement 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> (); // create a single-chain table} public HashSet () {this (97 );} private int hash (T x) {// use hashCode to solve 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 );}}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.