1. interpolation lookup is similar to binary lookup. It is used to search for an element on an ordered basis.
2. The principle of binary search is to take half of each time and compare it with the mid value to determine the range of the next search.
3. imagine finding a word in an English dictionary. Because it is arranged in alphabetical order, you are not stupid enough to use the binary search method. First, find half of the dictionary, take the dictionary 1/4 again... in this case, the efficiency is obviously not the fastest, and it is our turn to look up the difference.
4. Derivation of the difference formula:
Ordered sequence: 1 2, 3, 4, 5, 6, 7, 8, 9, 10
Proportional formula: assume that the array a [I] is ordered.
(Key-low)/A [Key]-A [low] = (high-low)/A [High]-A [low];
Key-Low = (high-low) * (a [Key]-A [low])/A [High]-A [low];
Key = low + (high-low) * (a [Key]-A [low])/A [High]-A [low];
Replace the key with the mid location, that is, the key location. In this case, replace the key location with the mid location, a [Key] with the key location, and the value to be searched, that is, we need to find whether the location on the Mid is equal to the key
Mid = low + (high-low) * (key-A [low])/A [High]-A [low];
5. Two conditions to be met for the difference value search:
A. Each access to data is expensive compared with the general instructions. For example, the table to be searched must be in the disk rather than the memory, so disk access is required for each comparison. In this case, the efficiency advantage of searching can be clearly reflected.
B. data Tables are ordered and evenly distributed, such as phone book and dictionary. for example, {1 2, 3, 4, 6, 7, 8, 9, 10} is evenly distributed, while {1, 3, 7, 11, 16, 21, 27 ...} it is not evenly distributed. in this case, the difference search and binary search are compared, and the advantage is not obvious.
The Code is as follows:
# DEFINE _ crt_secure_no_warnings # include <stdio. h> # include <stdlib. h> int bin_search (int * a, int key, int N) {int low, high, mid; Low = 0; high = n-1; while (low <= high) {mid = low + (high-low) * (key-A [low])/(A [High]-A [low]); // different in binary lookup, apply the interpolation formula if (a [Mid]> key) // if the key is smaller than the interpolation value, set the high value to the next position under the interpolation parameter high = mid-1; else if (a [Mid] <key) Low = Mid + 1; else return mid;} return-1;} int Maina () {in T a [] = {1, 5, 17, 25, 33, 38, 46, 55, 69, 75, 99}; int key; int Len = sizeof () /sizeof (* A); printf ("Enter the value to be searched: \ n"); scanf ("% d", & Key); int Pos = bin_search (, key, Len); If (Pos! =-1) printf ("% d in the array position: % d \ n", POS + 1, key ); else printf ("elements not found in the array: % d \ n", key); System ("pause"); Return 0 ;}
What is difference search?