[Data structure] Search Algorithm: Binary Search and sequential search

Source: Internet
Author: User

I entered school in September and graduated in July. It ended my pleasant and rich college life at the Software Institute. This series is a review of the four-year study of professional courses, see: http://blog.csdn.net/xiaowei_cqu/article/details/7747205

Search Algorithm

A search algorithm searches for a specific target in an existing sequence (list). Each record in the sequence must be associated with a key to search. The search algorithm usually requires two inputs: 1. Search sequence 2. Search Keyword Search Algorithm output parameters and return values: 1. The returned value of error_code indicates whether the search is successful. 2. if the search is successful, success is returned. The output parameter position locates at the destination. 3. If the search fails, not present is returned, the output parameter may be undefined or different from any values in the existing position. The idea of an algorithm for sequential search is simple: Start from the first element of the table one by one, if the element is consistent with the target element, the search is successful. If the last element still does not have the target element, the search fails. [Lab description]

Topic: compile a program to query the sequence table {,} in sequence with the keyword 5. Required output:
1) original sequence table; 2) locate the keyword; 3) number of comparisons.
1. First, you must write a list of class tables. Insert () according to the most basic operation, obtain retrieve (), and obtain the size ().
2. we observe the topic requirements. Although the table stores simple integers, if we use the list <int> object, we obviously cannot record the comparison times, therefore, we write a class key to record the values stored in the table through its internal int type data member, and mimic the basic logical operations of the int type, that is, write the heavy-load logical operators, at the same time, add a static data member comparisons to record the number of comparative operations.
3. After preparation, write the sequential search algorithm. The algorithm is simple and easy to implement. When the first element in the table is compared and the target is found, the position of the element in the table is returned. If no target exists after traversal, the search fails, -1 indicates that the table has no target element. 4. Compile the final output function as required by the question. [Related Code] function sequential_search

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

Binary Search Algorithm

The premise of binary search is that the table is a standard table in ascending or descending order. The incremental table is used in this experiment.
The binary search starts from the middle of the table to find the target element. If the consistent element is found, the search is successful. If the middle element is smaller than the target element, the second half of the table is still searched by the binary search method (the table is incrementally arranged). If the middle element is larger than the target element, search for the first half of the table. [Lab description]

Topic: compile a program to query the ordered table {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} using a binary search keyword 9. Required output:
1) original sequence table; 2) locate the keyword; 3) number of comparisons.
1. The premise of the binary search algorithm is that the table must be ordered. For example, the question is an incremental table. To achieve the order of tables, on the one hand, we can standardize user input, and on the other hand, we can also write ordered classes to facilitate user input.
Therefore, the derived class oredered_list in the list is used to rewrite the error_code insert (INT position, const Record & Data) function, so that insertion cannot be performed if the inserted position does not meet the table's ordering conditions.
At the same time, write the inserted overload function error_code insert (const Record & data), which can be directly inserted to the appropriate location for user input.
2. The key in question 1 is still used to indicate the target.
3. Implement the binary search algorithm. Through the learning in the book, we directly use the binary search algorithm that adds equal judgment. That is to say, each time the table starts to compare the middle elements. If the target element is obtained, the position in the table where the element is located is returned. If the middle element is smaller than the target element, the right half part will continue to be searched in two parts; otherwise, perform binary search for the first half of the table. If no target element exists at the end,-1 is returned to indicate that the table has no target element. 4. Use the output function compiled in question 1 to output the result.
/* Note that ordered_list is derived from list, so although the first parameter type in the print_out function is list <int>, it can still be used, instead of writing overload functions */[related Code]

Function binary_search

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)>>1; 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: [Result Analysis] a. Sequence search algorithm is implemented.

1. The idea of sequential search is very simple. It is a traversal idea. It is easy to find target elements one by one.
2. Applicable sequence search for tables with n elements. Number of comparisons: unsuccessful: N comparisons. Successful search: The best case is 1 time, that is, the first element is the target element; the worst case is n times; the average number of comparisons (n + 1)/2.
Therefore, when a table is large, sequential search costs a lot.
3. the sequential search algorithm does not show repeated comparisons, that is, once it is found, it is successful, but the cost is that when the table has repeated target elements (such as multiple target elements) we can only get the position of the first element. B. Implement the Binary Search Algorithm

1. the binary search method is used to find a table in ascending order. First, you can start from the middle element. If the element is smaller than the target element, you can find the second half of the table. Otherwise, you can find the First Half of the table, and repeat this process. In this way, the length of the table is halved during each search.
2. binary Search involves both bottom and top in implementation. The process of halving each time is reflected in the changes of bottom and top. In code implementation, you can use pure loops or function recursion.
Recursive thinking is easier to understand, but after writing it, we find that the function is tail recursion. The tail recursion can usually be implemented using a simple loop, and the loop does not have the function call process in the operation, saves time and space.
3. Changes to the Code in Small and Medium-sized areas may greatly change the program.

For example, the above two binary search binary_search_1 (not equal to the case) binary_search_2 (add equal to the situation) Experimental code download: http://download.csdn.net/detail/xiaowei_cqu/4437702 (reproduced please indicate the author and the source: http://blog.csdn.net/xiaowei_cqu is not allowed for commercial use)

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.