Lookup algorithm: Binary lookup, sequential lookup, lookup algorithm

Source: Internet
Author: User
Tags logical operators

September 08 Admission, July 12 graduation, ended my happy and rich university life in the Software Institute. This series is a review of the four-year professional curriculum study, indexed in: http://blog.csdn.net/xiaowei_cqu/article/details/7747205


Lookup algorithm
The lookup algorithm looks for a particular target in the existing sequence (list), requiring that each record in the sequence must be associated with a keyword (key) in order to find it.
The lookup algorithm usually requires two inputs: 1, the lookup sequence 2, the keyword lookup algorithm's output parameters and return value: 1, the return type is Error_code value to indicate whether to find success 2, if the lookup succeeds, returns success, the output parameter position navigates to the target At position 3, if lookup fails, returns not present, the output parameter may be undefined or different from any value in the existing location
Sequential lookup algorithm
The idea of the sequential lookup algorithm is simple: Start a lookup down from the first element of the table and find success if there are elements that are consistent with the target; if the last element still has no target element, then the lookup fails.

"Experiment description" topic: Write a program for sequential table {3,6,2,10,1,8,5,7,4,9}, in order to find the key word 5 process. Output Required:
1) The original order table, 2 finds the position of the keyword, 3 compares the number of times.
1. First write the Class table list. You need to meet the most basic operation inserts insert (), get Retrieve (), and get size ().
2. We observe the topic requirements, although the table is stored in a simple integer, but if we use the List<int> object obviously can not record the number of comparisons, so we write a class key through its internal int type of data members to record the values stored in the table, And imitate the basic logical operation of int, which is to write overloaded logical operators while adding a static data member comparisons the number of times it is used to record comparison operations.
3. After the preparation is done, start to write sequential lookup algorithm. The idea of the algorithm is simple and easy to implement, starting from the first element of the table, the target returns the position in the table where the element is located; If there is no target after traversal, then the lookup fails, and return-1 indicates that there are no target elements in the table. 4. Write the final output function according to the topic requirement.
The related code function  sequential_search [cpp]  view plain copy int sequential_search (const list<int>  &the_list,                          const key &target)   /*Post:  If an entry in the_list is equal to target, then  return the position          of this entry.            Otherwise return -1   */    {       int position;       int s= The_list.size ();       for (position=0;position<s;position++) {           int data;            the_list.retrieve (Position,data);           if (data==target) {                return position;            }       }       return -1;  }  
Two-point search algorithm
The second search premise is that the table is a specification table in ascending or descending order. In this experiment we used an increment table.
The binary lookup starts from the middle of the table to find the target element. If a consistent element is found, the lookup succeeds. If the intermediate element is smaller than the target element, the second half of the table is still found using the binary lookup method (the table is incremented), whereas the middle element is larger than the target element, and the first half of the table is found.

"Experiment description" topic: Write a program, to the ordered table {1,2,3,4,5,6,7,8,9,10}, using a binary lookup keyword 9 process. Output Required:
1) The original order table, 2 finds the position of the keyword, 3 compares the number of times.
1. Two-point lookup algorithm is based on the premise that the table must be ordered, such as the title is an incremental arrangement of the table. To realize the order of the table is a user specification input, on the other hand we can also write ordered classes to facilitate user input.
So from the list of derived classes oredered_list, rewrite the function error_code insert (int position,const record &data), so that the inserted position does not meet the table's ordered conditions, cannot be inserted.
At the same time, write the overloaded functions inserted error_code insert (const record &data), you can directly insert into the appropriate location to facilitate user input.
2. Still use the key in topic 1 to indicate the goal
3. Realize the binary lookup algorithm. Through the study in the book, we directly use the addition of equality judgment of the binary lookup algorithm. That is, each time the middle element of the table is compared, the position in the table of the element is returned if the target is obtained, and if the intermediate element is less than the target element, the right half continues to find the second part, whereas the first half of the table is divided into two points. If there is no target element in the end, return-1 is used to indicate that there are no target elements in the table.
4. The output function, which is still written using topic 1, outputs the result.
/* Note here because Ordered_list is derived from the list, the first parameter type in the Print_out function is List<int&gt, and can still be used without writing overloaded functions.

The related code function  binary_search [cpp]  view plain copy int binary_search (const ordered_list<int>  &the_list,                        const key &target)   /*post: if an  entry in the_list is equal to target, then return the  position          of this entry.            Otherwise return -1   */   {        int position;       int data;        int bottom=0,top=the_list.size () -1;       while (bottom<=top) {            position= (bottom+top) &GT;&GT;1;&NBSP;&NBSP;&NBsp         the_list.retrieve (position,data);            if (data==target)                 return position;            if (data<target) bottom=position+1;           else  top=position-1;       }       return -1;   }  
"Process Record" experiment screenshot:

"Result Analysis"
A. Implementing sequential lookup algorithms 1. Sequential lookup algorithm The idea is very simple, is a kind of traversal of thought, find the target element, realize also very simple.
2. For tables with n elements, the order lookup is applicable. Compare times: unsuccessful: compare n times. Successful lookup: The best case is 1 times, that is, the first element is the target element, the worst case is n times, the average number of comparisons (n+1)/2 times.
So when the table is large, the cost of sequential lookup is great.
3. The sequential lookup algorithm does not have duplicate comparisons, i.e. success if found, but at the same time, when there are duplicate target elements in the table (for example, with multiple target elements) we can only get the position of the first element.
B. Implementation of the binary lookup algorithm 1. Two points to find the idea: the incremental arrangement of the table, first from the middle element to find, if the element is smaller than the target element, then find the second half of the table, instead of looking for the first half of the table, and repeat the process. In this way we halve the length of the table in each lookup.
2. Two points to find in the implementation of the amount of bottom and top, each of the process of halving the bottom and a change, in the implementation of the code can use a simple loop or the idea of recursive function.
Recursive thinking is easier to understand, but after writing we found that the function is the tail recursion, tail recursion can usually be implemented in a simple loop, the loop in the operation without the process of function calls, save time and space.
3. Changes in small areas of coding may greatly improve the procedure.
such as the two kinds of binary lookup binary_search_1 (not equal to the case) binary_search_2 (add equals condition)



Experimental code Download: http://download.csdn.net/detail/xiaowei_cqu/4437702 (reprint please specify the author and source: Http://blog.csdn.net/xiaowei_cqu Do not use for commercial purposes without permission

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.