Search algorithm Summary (binary lookup/Two fork find tree/red black tree/Hash list)

Source: Internet
Author: User

1, two-point search

When a binary lookup is found, the key to be looked up and the middle key of the sub-array is compared first. If the key being found is less than the middle key, the left Subarray continues to look up, if it is greater than the middle key, it is found in the right sub-array, otherwise the middle key is the element to be found.

/*** Two-point search*/ Public classBinarySearch { Public Static intFindint[] Array,intkey) {        intleft = 0; intright = Array.length-1; //while (left <= right) cannot be changed to <, otherwise the condition is incomplete.         while(Left <=Right ) {            intMid = left + (right-left)/2; if(Key = =Array[mid]) {                returnmid; } Else if(Key <Array[mid]) { Right= Mid-1; } Else{ Left= Mid + 1; }        }        return-1; }}

Each time you move the left and right pointers, you need +1 or 1 on the base of the mid to prevent a dead loop and the program will run correctly.

But if the conditions change a little bit, will you write? For example, the data in the array may be repeated, requiring the smallest (or largest) subscript of the matched data to be returned, and, more recently, the index of the first element in the array that is greater than key (i.e. the smallest element larger than key), and so on. These, although only a little bit of change, the realization of the time really need to be more careful. The implementation of these binary search variants is shown in:luoxn28/algorithm_data_structure.

2, Binary search tree

Binary lookup tree for each node in the tree X, its left subtree all the keywords are less than the keyword of x, and all the keywords in its right subtree are greater than the X keyword.

Binary lookup Tree The main operation is to find and insert the process as shown:

two fork Find tree node classes are as follows:

/***/class  Node    {//  ---------------------------------- -Instance Variablespublic      Node left;      Public Node right;      Public int data;}

Two forks find the tree class code as follows:

/*** Binary search Tree class*/ Public classBinaryTree {//-----------------------------------Instance Variables     PublicNode Root;//root node     Public intNodes//Number of nodes//-----------------------------------Constructors     PublicBinaryTree () {root=NULL; Nodes= 0; }    //-----------------------------------Public Methods     Public voidInsertintdata) {Root=insertinternal (root, data); }     Public voidRemoveintdata) {        if(find data)! =NULL) {root=removeinternal (root, data); Nodes--; }    }     PublicNode Find (intkey) {Node Node=Root;  while(Node! =NULL) {            if(Key = =node.data) {returnnode; } Else if(Key <node.data) {node=Node.left; } Else{node=Node.right; }        }        return NULL; }     PublicNode min () {if(Root = =NULL) {            return NULL; } node Node=Root;  while(Node.left! =NULL) {node=Node.left; }        returnnode; }     PublicNode Max () {if(Root = =NULL) {            return NULL; } node Node=Root;  while(Node.right! =NULL) {node=Node.right; }        returnnode; } @Override PublicString toString () {if(Root! =NULL) {StringBuilder buff=NewStringBuilder ();            Tostringinternal (root, Buff); returnbuff.tostring (); }        return""; }    //-----------------------------------Private Methods    PrivateNode NewNode (intdata) {Node Node=NewNode (); Node.data=data; Node.left= Node.right =NULL; returnnode; }    Private voidtostringinternal (node node, StringBuilder buff) {if(Node! =NULL) {tostringinternal (node.left, Buff); Buff.append (Node.data+ " ");        Tostringinternal (node.right, Buff); }    }    PrivateNode insertinternal (node node,intdata) {        if(node = =NULL) {node=NewNode (data); Nodes++; } Else if(Data <node.data) {node.left=insertinternal (node.left, data); } Else if(Data >node.data) {node.right=insertinternal (node.right, data); }        returnnode; }    PrivateNode removeinternal (node node,intdata) {        if(node = =NULL) {            return NULL; } Else if(Data <node.data) {node.left=removeinternal (node.left, data); } Else if(Data >node.data) {node.right=removeinternal (node.right, data); } Else if(Node.left! =NULL&& Node.right! =NULL) {Node tmp=min (node.right); Node.data=Tmp.data; Node.right=removeinternal (Node.right, tmp.data); } Else{//Delete node has a child node or no child node            if(Node.left! =NULL) {node=Node.left; } Else if(Node.right! =NULL) {node=Node.right; } Else{node=NULL; }        }        returnnode; }    Privatenode min (node node) {if(node = =NULL) {            return NULL; }         while(Node.left! =NULL) {node=Node.left; }        returnnode; }}

The above is the code implementation of the two-fork lookup tree, and a balance lookup tree is an AVL tree, similar to a two-fork lookup tree. An AVL tree is a two-fork lookup tree that has a maximum height difference of 1 for the Saozi right subtree of each node . (Suppose the height of the empty tree is defined as 0). For the AVL tree, see Tree-Data structure (binary lookup tree, AVL tree).

3. Red and black trees

Red and black trees are a kind of balanced tree, ensuring that the worst-case operation time Complexity is O (LGO (n)). Red and black trees are widely used, such as the underlying data structure of STL's set and map in C + +, and the underlying data structures of TreeSet and TreeMap in Java collections. Learn the red and black trees, you can use the two-fork search tree as a reference, this will help deepen understanding. The operation of red and black tree mainly includes rotation, inserting and deleting of nodes.

Red and black tree explanation and implementation click: deep understanding of red and black trees

4. Hash list

Hashing is a technique used to perform insertions, deletions, and lookups with constant average time. The ideal hash data structure is simply a fixed-size array that contains a keyword. Typically, a keyword is a string with related values (payroll information, and so on).

The main problem of hash function is to solve the problem of conflict elimination. If another element already exists (the hash value exists) when one element is inserted, a conflict occurs. There are several ways to resolve this conflict, usually the simplest two: the separation link method and the open address method.

The hash table class code is as follows:

/*** Hash Table class*/ Public classHashlist {//-----------------------------------Instance Variables    PrivateList<list<integer>>Array; Private intcapacity;//Hash Table Size//-----------------------------------Constructors     Publichashlist () { This(47); }     PublicHashlist (intcapacity) {         This. Capacity =capacity; if(Capacity < 47) {             This. Capacity = 47; } Array=NewArraylist<list<integer>>();  for(inti = 0; I < capacity; i++) {Array.add (NewArraylist<integer>()); }    }    //-----------------------------------Public Methods     Public BooleanFindintdata) {        intindex =hash (data); List<Integer> list =Array.get (index); if(List.contains (data)) {return true; }        return false; }     Public voidInsertintdata) {        intindex =hash (data); List<Integer> list =Array.get (index); if(!list.contains (data))        {list.add (data); }} @Override PublicString toString () {StringBuilder buff=NewStringBuilder ();  for(inti = 0; I < array.size (); i++) {List<integer>list =Array.get (i); Buff.append (i+ ": "); Buff.append (List+ "\ n"); }        returnbuff.tostring (); }    //-----------------------------------Private Methods     Public intHashintdata) {        return(Data%capacity); }}

Resources:

1,luoxn28/algorithm_data_structure

Search algorithm Summary (binary lookup/Two fork find tree/red black tree/Hash list)

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.